Getting session data of logged in users in java
I am working with servlets. When my user logs in, my application is setting his userId and deviceId in a session variable开发者_开发百科.
Some other part of my application now needs the list of online people and their userId/ deviceId. Note that a user may have simultaneous logins with 2 devices, so we have 2 deviceIds for the same userId.
How should I approach this situation ? I am not willing to use database for tracking the login/ logout functionalities
Store this information also in HttpServletContext's attribute. This context is global per servlet and can be accsessible by all sessions.
You even can do more. Using HttpSessionAttributeListener you can be notified every time the attribure is added, so if you want to create some kind of monitor application it may be more responsive.
In addition to Alex's response. The header attribute you are looking for is user-agent. Following is the code snippet of accessing browser type from request.
((javax.servlet.http.HttpServletRequest)pageContext.getRequest()).getHeader("user-agent")
In addition to Alex and Suken's responses, assuming the user has a single session you could store the deviceId's in a Map:
String userAgent = (see Suken's response)
String deviceId = request.getParameter("REQUEST_PARAMETER_DEVICE_ID");
Map<String, String> devices = request.getSession().getAttribute("SESSION_ATTRIBUTE_DEVICES");
if (devices == null) {
devices = new HashMap<String, String>();
request.getSession().setAttribute("SESSION_ATTRIBUTE_DEVICES", devices);
}
devices.put(userAgent, deviceId);
This makes sure the multiple devices remain visible and are not overwritten. You still need to expose them like Alex explained if you want to access them at application level.
精彩评论