Capture information and use when you need Java

0

I'm thinking of implementing a function that captures the logged in user, I still can not figure out how I can implement that function, I'd like to know what's usual and conducive for me to record the user's name and code while the software runs. My application is made in Java.

    
asked by anonymous 12.06.2015 / 15:40

1 answer

2

If your application is web, this information is usually saved in the application session. Here's a good explanation of sessions:

link

If your application is desktop, you can save it to a Map that is publicly accessed as a singleton and synchronized. Here's the definition of singleton:

link

Session

The following is an example using HTTP Session for servlets:

....
import javax.servlet.http.HttpSession;
....



@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
....


    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {


        // recupera a sessõa
        HttpSession session = request.getSession();

        // colocar um valor na sessão
        session.setAttribute("user", "Pankaj");

        ....

        // recupera valor da sessão
        String userName = (String) session.getAttribute("user");

        ....

    }

....

}

Desktop

See a class that could be used for a Desktop session:

package com.myapp.session;


import java.util.Hashtable;
import java.util.Map;

public class Session {

    // note that HashTable is synchronized
    private Map<String, Object> _map = new Hashtable<String, Object>();

    private static Session _session = new Session();

    public static Session getSession() {
        return _session;
    }

    public void setAttribute(String key, Object value) {
        _map.put(key, value);
    }

    public Object getAttribute(String key) {
        return _map.get(key);
    }
}

Then, to use the session do the following:

Session session = Session.getSession();
....
// coloca um valor na sessão
session.setAttribute("user", "Pankaj");

....

// recupera valor da sessão
String userName = (String) session.getAttribute("user");
    
12.06.2015 / 16:44