views:

173

answers:

2

Suppose I have a web app with a servlet defined in web.xml.

Then I deploy it on Tomcat.

Then I open my browser and go to the link to this servlet, it is invoked.

Then I close my browser window.

How Session behaves ? How is it created, destroyed in this case?

if this servlet is "detached" from all the web app, and gets parameters only using post & get, so it does not need Session at all, should one use Session.invalidate at the end of doGet(), doPost() ?

+3  A: 

The servlet container usually keeps track of session using either (1) a HTTP cookie or (2) adding an extra parameter jsessionid in each URL.

When a user access this site and no session exist already, a new one is created for him, including the corresponding HttpSession. If necessary, the user might be redirected to a login page.

The effect of Session.invalidate will basically be: "Discard the current session for this user. If he access another page on the site, a new session will be created".

So far I know, session invalidation is used typically to implement logout feature.

I wouldn't call Session.invalidate in your "detached" servlet, it will interfere with the other pages. Basically, you don't care about the session in your servlet, you don't use it anyway.

Maybe have also a look at this question about disabling the session.

ewernli
+3  A: 
Then I close my browser window.
How Session behaves ? How is it created, destroyed in this case?

Are you asking what happens if the browser is closed even before the response is received back at the client?

In such a case, a Session will still be created on the server. It will persist for a specified time period and then expire.

The next request from your browser will create a new Session. See more on this here: http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpSession.html

Regarding session.invalidate ewernli has already answered.

JoseK
@josek Ok, but I do not need 1000 sessions to be expired AFTER a certain time period. I know I simply don't need it, and as far as it is created on each request, then it would be perfect to manually destroy it after my business logic method IS OVER.
EugeneP
It depends on what the servlet is actually doing. Is the user not going to continue any journey on the site?The HttpSession in this case will be very lightweight, less than 1 Kb, since you're not storing anything into it. So there is no Major impact on the server.
JoseK
@josek Very good.
EugeneP