EugeneP
EugeneP

Reputation: 12003

Servlet Session behavior and Session.invalidate

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() ?

Upvotes: 1

Views: 10091

Answers (2)

JoseK
JoseK

Reputation: 31371

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.

Upvotes: 3

ewernli
ewernli

Reputation: 38625

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.

Upvotes: 4

Related Questions