views:

38

answers:

2

Hi,

I've a JSP/Servlet Web App that consist of more than one servlet (and some JSPs)

I need to create an new HttpSession whenever the users access servlet A, knowing that, servlet A is the home page (i.e. he access it as the first servlet/page in the application)

so far so good, I can write the following code at the start of the servlet A:

HttpSession session = request.getSession(false);
if (session == null) {  
    logger.debug("starting new session...");
    session = request.getSession();
    // other staff here
}

But the problem is, if the user didn't close his browser (even if he closes the tab - in firefox for instance - the session will still be open), so when he try to open my site again, the last session will be re-used (in the rage of session timeout ofcourse), and this I don't need. I need whenever he access Servlet A, he got created a brand new HttpSession.

but unfortunately, he may access this servlet twice per session based on some scenario!!

Please help.

+1  A: 

You should store some information (attribute) in the session that it's been used. And if it has been, invalidate

HttpSession session = request.getSession();

Object isOld = session.getAttribute( "isOld" );

if ( isOld != null )
{
  session.invalidate( );

  // Recreate session
  session = request.getSession( );
}

session.setAttribute( "isOld", new Object( ) );
Alexander Pogrebnyak
+2  A: 

It seems to me that you should not be using session for this purpose. Perhaps you can add a parameter to request (i.e. transaction id) and pass it around trough all your related requests, so when user would close page the transaction id would be gone. Then you can store any data associated with given transaction id in the http session or elsewhere and could also clean it after some time.

The spring framework has an abstraction called bean scope, which seem like a good fit for your scenario, so you can create a custom scope for your transaction (or user's session) and store all the data in some bean scoped with such custom scope.

Eugene Kuleshov