Http Sessions life cycle in Tomcat - java

I have a task to show to the site admin a list of user names and how many tomcat sessions are currently utilized by each user (along with some other support-related information).
I keep authenticated users as the application context attribute as follows (sparing unnecessary details).
Hashtable<String, UserInfo> logins //maps login to UserInfo
where UserInfo is defined as
class UserInfo implements Serializable {
String login;
private transient Map<HttpSession, String> sessions =
Collections.synchronizedMap(
new WeakHashMap<HttpSession, String>() //maps session to sessionId
);
...
}
Each successful login stores the session into this sessions map.
My HttpSessionsListener implementation in sessionDestroyed() removes the destroyed session from this map and, if sessions.size() == 0, removes UserInfo from logins.
From time to time I have 0 sessions showing up for some users. Peer reviews and unit testing show that the code is correct. All sessions are serializable.
Is it possible that Tomcat offloads sessions from memory to the hard drive, e.g. when there is a period of inactivity (session timeout is set to 40 minutes)? Are there any other scenarios where sessions are 'lost' from GC point of view, but HttpSessionsListener.sessionDestroyed() wasn't invoked?
J2SE 6, Tomcat 6 or 7 standalone, behaviour is consistent on any OS.

As this question got close to 5k views, I think it would be beneficial to provide an example of a working solution.
The approach outlined in the question is wrong - it will not handle server restarts and will not scale. Here is a better approach.
First, your HttpServlet needs to handle user logins and logouts, something along these lines:
public class ExampleServlet extends HttpServlet {
#Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String action = req.getParameter("do");
HttpSession session = req.getSession(true);
//simple plug. Use your own controller here.
switch (action) {
case "logout":
session.removeAttribute("user");
break;
case "login":
User u = new User(session.getId(), req.getParameter("login"));
//store user on the session
session.setAttribute("user",u);
break;
}
}
}
The User bean has to be Serializable and has to re-register itself upon de-serialization:
class User implements Serializable {
private String sessionId;
private String login;
User(String sessionId, String login) {
this.sessionId = sessionId;
this.login = login;
}
public String getLogin() { return login; }
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
//re-register this user in sessions
UserAttributeListener.sessions.put(sessionId,this);
}
}
You will also need an HttpAttributeListener to handle session lifecycle properly:
public class UserAttributeListener implements HttpSessionAttributeListener {
static Map<String, User> sessions = new ConcurrentHashMap<>();
#Override
public void attributeAdded(HttpSessionBindingEvent event) {
if ("user".equals(event.getName()))
sessions.put(event.getSession().getId(), (User) event.getValue());
}
#Override
public void attributeRemoved(HttpSessionBindingEvent event) {
if ("user".equals(event.getName()))
ExampleServlet.sessions.remove(event.getSession().getId());
}
#Override
public void attributeReplaced(HttpSessionBindingEvent event) {
if ("user".equals(event.getName()))
ExampleServlet.sessions.put(event.getSession().getId(),
(User)event.getValue());
}
}
Of course, you will need to register your listener in web.xml:
<listener>
<listener-class>com.example.servlet.UserAttributeListener</listener-class>
</listener>
After that, you can always access the static map in UserAttributeListener to get an idea of how many sessions are running, how many sessions each user is using etc. Ideally, you would have a bit more complex data structure warranting its own separate singleton class with proper access methods. Using containers with copy-on-write concurrent strategy might also be a good idea, depending on the use case.

Instead of writing something from scratch, check out psi-probe.
http://code.google.com/p/psi-probe/
This may just be a simple drop in that solves your problems.

Do you find that you get the issue following a restart of Tomcat? Tomcat will serialize active sessions to disk during a successful shutdown and then deserialize on startup - I'm not sure whether this will result in a call to your HttpSessionListener.sessionCreated() as the session isn't strictly created, just deserialized (this may be not be correct(!), but can be tested fairly easily).
Have you also compared your results with the Tomcat managers session stats? It keeps track of the number of active sessions, and should tie up with your figures, if not, you know your code is wrong.
Also, probably unrelated to your issue, but is there a good reason why you are using Hashtable and WeakHashMap? I tend to go with ConcurrentHashMap if i need a thread safe Map implementation, its performance is much better.

When a client visits the webapp for the first time and/or the HttpSession is obtained for the first time via request.getSession(), the servlet container creates a new HttpSession object, generates a long and unique ID (which you can get by session.getId()), and store it in the server's memory. The servlet container also sets a Cookie in the Set-Cookie header of the HTTP response with JSESSIONID as its name and the unique session ID as its value.
As per the HTTP cookie specification (a contract a decent web browser and web server have to adhere to), the client (the web browser) is required to send this cookie back in subsequent requests in the Cookie header for as long as the cookie is valid (i.e. the unique ID must refer to an unexpired session and the domain and path are correct). Using your browser's built-in HTTP traffic monitor, you can verify that the cookie is valid (press F12 in Chrome / Firefox 23+ / IE9+, and check the Net/Network tab). The servlet container will check the Cookie header of every incoming HTTP request for the presence of the cookie with the name JSESSIONID and use its value (the session ID) to get the associated HttpSession from server's memory.
The HttpSession stays alive until it has not been used for more than the timeout value specified in <session-timeout>, a setting in web.xml. The timeout value defaults to 30 minutes. So, when the client doesn't visit the web app for longer than the time specified, the servlet container trashes the session. Every subsequent request, even with the cookie specified, will not have access to the same session anymore; the servlet container will create a new session.
On the client side, the session cookie stays alive for as long as the browser instance is running. So, if the client closes the browser instance (all tabs/windows), then the session is trashed on the client's side. In a new browser instance, the cookie associated with the session wouldn't exist, so it would no longer be sent. This causes an entirely new HTTPSession to be created, with an entirely new session cookie begin used.

Related

Disabling Cookies stops Session as well?

I have been building a Web Application, So far I have implemented Login & Registration. User can register and then can login within the web application. Everything is working fine. What I am doing is When user clicks on Login button, a servlet is being invoked where I'm checking if the credentials are correct, If validated then Saving isLoggedIn in HttpSession and redirecting it to Home Page.
LoginServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
boolean isValidated = false;
... // Service Layer is invoked here and checks for user validation
// Assume isValidated to be true
if(isValidated){
HttpSession session = request.getSession();
session.setAttribute("isLoggedIn", Boolean.valueOf(true));
...
// redirected to /home
}else{
// redirected to /login?invalid
}
}
HomeController.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
HttpSession session = request.getSession();
Boolean isLoggedIn = (Boolean) session.getAttribute("isLoggedIn");
if(isLoggedIn != null && isLoggedIn){
...
// Service Layer is invoked to fetch `Home Page Data`
}else{
// redirected to /login?expired
}
}
All of a sudden I have encountered a strange problem, If i disable cookies for localhost using FireBug I am not able to login anymore. No matter if I enter correct username or password each time I am being redirected to /login?expired.
I don't get it, Cookies are ment to be stored at client side and Session are stored at Server side, then Why session attribute can not be set if Cookies are disabled.
I have tried disabling Cookies for already built Web Application in Spring-MVC which is in production and having same issue there as well.
When cookies are enabled, the session is stored in a cookie under the name JSESSIONID.
If cookies are disabled, the container should rewrite the session id as a GET parameter (i.e. &JSESSIONID=1223456fds at the end of all URLs).
If the URL rewriting isn't on by default, see your container's documentation on how to enable it.
You might want to consider modern frameworks (for example Spring MVC with Thymeleaf) which will automate this for you. Otherwise you need to make sure you're rewriting URLs with response.encodeURL() as Ouney directs in his answer.
A session is to maintain a stateful conversation between server and client.
By default Http is a stateless protocol.
So, to make it a stateful conversation we need to store some values on browser side (cookies) which are sent by the browser to the server with the request.
Without cookies every request is a new request and it becomes a stateless conversation.
That is the reason people use add session information in url's (jsessionId) when cookies are disabled.
To use URL rewriting use response.encodeURL() on your URLs.
with every request and response session id stored on client side as a Cookie is checked by server, if it is present the server update the information and if not a new session is created. so when you disable cookie in you browser, with every request a new session is created as cookie is disabled.
for further information you can refer this link.
click here
When we manage the session using the HttpSession mechanism that time a jsessionid save in the browser's cookies. So when you delete a cookies from the browser or disable cookies that time that jsessionid information is not sent to the server and that time server treat this request from a new session.

AngularJS+Atmosphere Websockets: Is it possible to retrieve attributes in AtmosphereResource from a HttpServlet?

I'm new to Atmosphere framework & websockets.
I'm developing a single page app, As a first step I want to implement a basic authentication using AngularJs(Client side) and Atmosphere websockets(server side).
For authentication, in the beginning, I have used normal servlets and saved the User bean in HttpSession. But later I understood, I can't access the session attributes in the class(websocket service)
#AtmosphereService(broadcaster = JerseyBroadcaster.class)
So, I have created another Login AtmosphereService, In which suspend method checks the user and if user exists, then stores UserBean in ConcurrentMap against uuid key using following method so that I can access in future.
public void createSession(AtmosphereResource resource) {
logger.debug("Create session ({})", resource.uuid());
ConcurrentMap<String, Object> session = new ConcurrentHashMap<String, Object>();
ConcurrentMap<String, Object> prevSession = sessionsByUuid.putIfAbsent(resource.uuid(), session);
if (prevSession != null) {
logger.warn("Session already exists ({})", resource.uuid());
}
}
So in the client side, As I have AngularJS and configured routes, when the user logged in, I store the user-key in a rootscope variable and when ever route changes it checks as follows.
$rootScope.$on("$routeChangeStart", function(event, next, current) {
aNext = next;
if (next.templateUrl != "./partials/login.html") {
if($rootScope.loggedUser !=null && $rootScope.loggedUser!=""){
$location.path(nextPage);
}else{
$rootScope.goLoginPage();
}
}
});
But now the problem is If user refresh the page it goes to login page, because the $rootScope.loggedUser will not contain any thing.
Before, when I used simple servlets for authentication I used a ajax call to the servlet to check the user exists in the session or not and if he exists I assigned the user-key in $rootScope.loggedUser and route used to change properly.
Now as I'm using AtmosphereService instead of normal servlets for authentication, how can I make a request to either a servlet(in which I should access AtmosphereResource) or should I write another AtmosphereService to get the stored UserBean?

Java : How to deal with multiple sessions in the servlet [duplicate]

This question already has answers here:
How do servlets work? Instantiation, sessions, shared variables and multithreading
(8 answers)
Closed 7 years ago.
I am new to Java EE. I have a site which requires a user to log in, and after the user logs in I would like the user to see his/her own item (e.g: shopping cart).
So that means I have to use a session to accomplish that. But how do I deal with multiple sessions?
For example multiple users login to the system as well as to the same servlet? However, can I keep multiple sessions in one servlet? Do I keep a record of each of them? How does it work?
Can someone give an example please ?
In servlet you have access to HttpServletRequest which provides you with a getSession() method. This methods returns session object (essentialy a key-value map), different for each user.
If you put something into that map (like shopping cart), you can retrieve it later - but only when the same user accesses the application again (not necessarily the same servlet).
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
session.getAttribute("cart");
//...
session.setAttribute("cart", whateverYouWant);
Sessions are maintained in the servlet container and looked up by session id (typically a cookie). You don't have to implement anything yourself.
Yes you can. The servlet container will keep track of them for you, so you shouldn't have to do that bookkeeping yourself. The Session object can be obtained from the HttpServletRequest in your servlet code. Since your code only has to concern itself with a single request at a time, there's generally not much pain in dealing with multiple sessions.
To deal with multiple users login in Servlets, create a session for each login as
HttpSession session = request.getSession();
public HttpSession getSession()
returns the current session associated with this request, or if the request does not have a session, creates one.
Each session will identify the users uniquely.
Now if user wants to change some data that is in database then after creating session, set attribute with that session with the information which can uniquely identify the user in database, for e.g. email_id as:
session.setAttribute("id",email_id of user);
This attribute can be retrieved later in another Servlet/JSP as:
String email_id = session.getAttribute("id");
This attribute will help in identifying the user who has sent request to server to update data in database or to do something else.
For more methods related to the session, refer the link:
http://www.javatpoint.com/http-session-in-session-tracking

What is session in Java? [duplicate]

This question already has answers here:
How do servlets work? Instantiation, sessions, shared variables and multithreading
(8 answers)
Closed 5 years ago.
So far I understand Httpsession concepts in Java.
HttpSession ses = req.getSession(true);
will create a session object, according to the request.
setAttribute("String", object);
will, bind the 'String', and value with the Session object.
getAttribute("String");
will return an object associated with the string, specified.
What I am not able to understand is: I am creating a session object like
HttpSession ses = req.getSession(true);
and setting a name for it by calling setAttribute("String", object);.
Here, This code resides inside the server. For every person, when he tries to login the same code in the server will be executed. setAttribute("String", object); in this method the string value is a constant one. So, each session object created will be binded by the same string which I have provided. When I try to retrieve the string to validate his session or while logout action taken the getAttribute("String"); ll return the same constant string value(Am I right!!?? Actually I don't know, I'm just thinking of its logic of execution). Then, how can I be able to invalidate.
I saw this type of illustration in all of the tutorials on the WEB. Is it the actual way to set that attribute? Or, real application developers will give a variable in the "String" field to set it dynamically
(ie. session.setAttribut(userName, userName); //Setting the String Dynamically.. I dono is it right or not.)
And my final question is
WebContext ctx = WebContextFactory.get();
request = ctx.getHttpServletRequest();
What do the two lines above do? What will be stored in ctx & request?
HttpSession ses = req.getSession(true); will creates new session means. What value stored in ses.
Some [random] precisions:
You don't need login/logout mechanisms in order to have sessions.
In java servlets, HTTP sessions are tracked using two mechanisms, HTTP cookie (the most commonly used) or URL rewriting (to support browsers without cookies or with cookies disabled). Using only cookies is simple, you don't have to do anything special. For URL re-writing, you need to modify all URLs pointing back to your servlets/filters.
Each time you call request.getSession(true), the HttpRequest object will be inspected in order to find a session ID encoded either in a cookie OR/AND in the URL path parameter (what's following a semi-colon). If the session ID cannot be found, a new session will be created by the servlet container (i.e. the server).
The session ID is added to the response as a Cookie. If you want to support URL re-writing also, the links in your HTML documents should be modified using the response.encodeURL() method. Calling request.getSession(false) or simply request.getSession() will return null in the event the session ID is not found or the session ID refers to an invalid session.
There is a single HTTP session by visit, as Java session cookies are not stored permanently in the browser. So sessions object are not shared between clients. Each user has his own private session.
Sessions are destroyed automatically if not used for a given time. The time-out value can be configured in the web.xml file.
A given session can be explicitly invalidated using the invalidate() method.
When people are talking about JSESSIONID, they are referring to the standard name of the HTTP cookie used to do session-tracking in Java.
I suggest you read a tutorial on Java sessions. Each user gets a different HttpSession object, based on a JSESSIONID request/response parameter that the Java web server sends to the browser. So every user can have an attribute with the same name, and the value stored for this attribute will be different for all users.
Also, WebContextFactory and WebContext are DWR classes that provide an easy way to get the servlet parameters.
As I understand it, your concerns are about separation of the different users when storing things in the HttpSession.
The servlet container (for example Tomcat) takes care of this utilizing its JSESSIONID.
The story goes like this :
User first logs onto website.
Servlet container sets a COOKIE on
the user's browser, storing a UNIQUE
jsessionId.
Every time the user hits the
website, the JSESSIONID cookie is
sent back.
The servlet container uses this to
keep track of who is who.
Likewise, this is how it keeps track
of the separation of data. Every
user has their own bucket of
objects uniquely identified by the
JSESSIONID.
Hopefully that (at least partially) answers your question.
Cheers
Your basic servlet is going to look like
public class MyServlet{
public doGet(HttpServletRequest req, HttpServletResponse res){
//Parameter true:
// create session if one does not exist. session should never be null
//Parameter false:
// return null if there is no session, used on pages where you want to
// force a user to already have a session or be logged in
//only need to use one of the two getSession() options here.
//Just showing both for this test
HttpSession sess = req.getSession(true);
HttpSession sess2 = req.getSession(false);
//set an Attribute in the request. This can be used to pass new values
//to a forward or to a JSP
req.setAttribute("myVar", "Hello World");
}
}
There is no need to set any attribute names for your session that is already done. As others have suggested in other answers, use cookies or URL re-writing to store the sessionID for you.
When you are dealing with the DWR WebContext, it is simply doing the same thing as above, just normally the Request object isn't passed into the method, so you use the WebContext to get that request for you
public class DWRClass {
public doSomething(){
WebContext ctx = WebContextFactory.get();
HttpServletRequest req = ctx.getHttpServletRequest();
HttpSession sess = req.getSession(); //no parameter is the same as passing true
//Lets set another attribute for a forward or JSP to use
ArrayList<Boolean> flags = new ArrayList<Boolean>();
req.setAttribute("listOfNames", flags);
}
}

How to access HTTP sessions in Java

How to get any http session by id or all currently active http sessions within web application (Java 2 EE) in an elegant way?
Currently I have a WebSessionListener and once session was created I put it in ConcurrentHashMap() (map.put(sessionId, sessionObj)), everything ok, I can retrieve HTTP session from that map in any time by session id, but it looks like the HttpSession objects will never finalize... Even session was invalidated the map still reference on invalidated session object... Also I have read this article and it looks like the WeakHashMap is not acceptable in my case...
In other words I need a possiblity to look in any HttpSession even get all currently active HttpSession and retrieve some attributes from there...
Please advice somebody :)
Update
I need to access HttpSession objects because of follwoing reason:
Sometimes user does some actions/requests that may impact the work of another concurrent user, for example admin should disable user account but this user currently working with the system, in this case I need to show a message to admin e.g. "user XXX is currently working with the system" hence I need to check if any HttpSession which holds credentials of user XXX already exists and active. So this is whay I need such possibility to get any http session or even all sessions.
My current implementation is: SessionManager which knows about all sessions (ConcurrentMap) and HttpSessionListener which put/remove session into SessionManager.
I was concerned about memory issues that may occure and I wanted to discusse this with someone, but currently I am clearly see that everything should works fine because all invalidated session will be removed from map when sessionDestroyed() method will be called...
Many thanks for your replays, but now I understood that problem was just imagination :)
As per your clarification:
Sometimes user does some actions/requests that may impact the work of another concurrent user, for example admin should disable user account but this user currently working with the system, in this case I need to show a message to admin e.g. "user XXX is currently working with the system" hence I need to check if any HttpSession which holds credentials of user XXX already exists and active. So this is whay I need such possibility to get any http session or even all sessions.
For this you actually don't need to know anything about the sessions. You just need to know which users are logged in. For that you can perfectly let the model object representing the logged in user implement HttpSessionBindingListener. I of course assume that you're following the normal idiom to login/logout user by setting/removing the User model as a session attribute.
public class User implements HttpSessionBindingListener {
#Override
public void valueBound(HttpSessionBindingEvent event) {
Set<User> logins = (Set<User>) event.getSession().getServletContext().getAttribute("logins");
logins.add(this);
}
#Override
public void valueUnbound(HttpSessionBindingEvent event) {
Set<User> logins = (Set<User>) event.getSession().getServletContext().getAttribute("logins");
logins.remove(this);
}
// #Override equals() and hashCode() as well!
}
Then somewhere in your admin app, just obtain the logins from ServletContext:
Set<User> logins = (Set<User>) servletContext.getAttribute("logins");
Generally speaking, your servlet container will have its own session manager, which is responsible both for maintaining the lifecycle of the sessions, and associating incoming requests with the appropriate session (via cookies, anchor parameters, whatever strategy it wants).
The elegant way to do this would be to hook into this session manager in whatever way it allows. You could subclass the default one, for example, to allow you to get access to arbitrary sessions.
However, it sounds like what you're doing belies an underlying problem with your architecture. The data contained within a session should be specific to that session, so in general you shouldn't need to look up an arbitrary one in order to provide the standard logic of your web application. And administrative/housekeeping tasks are usually handled for you by the container - so again, you shouldn't need to interfere with this.
If you gave an indication of why you want access to arbitrary sessions, chances are that an alternative approach is more suited to your goals.
Andrzej Doyle is very right. But if you really, really want to manage your own list of sessions, then the way to connect to your container is via the HttpSessionListener - example code.
The listener is called whenever a new session is created, and importantly, it's also called when a session is destroyed; this will allow you to mimic the container's session bookkeeping.
You use your web.xml to register your session listener as a lifecycle listener for your your app.
You can communicate your session list with other processes in the container using the ServletContext, or you can cook up a more dirty scheme using e.g. static class fields.

Categories

Resources