J2EE: Useful methods of HttpSession

1. How to get the session id from HttpSession?

you can retrieve session id by calling getId() on the HttpSession object.

HttpSession session  = request.getSession();
sessoin.getId(); // returns session id.

2. How to know whether the session is new or old?

To know whether the session is new or old, you can use isNew() on HttpSession object. It returns true, if the session is created during the current request, which means the user's browser has not yet received the session id.

HttpSession session = request.getSession();
boolean isSessionNew = session.isNew();

3. How to change the maximum inactive interval time for a session?

setMaxInactiveInterval() enables you to change the inactivity window. This overrides the value you set in in web.xml for that specific session. you can make it shorter or longer based on your requirement. 

Why do u want to change inactive interval? Lets consider some scenario, where you want to increase the inactivity interval for some administrative users in your application or shorten the interval for some other users. In this case this method comes handy.

4. How to implement logout functionality in your web application?

use invalidate() for this purpose. This is the most important method in HttpSession.  calling invalidate() destroys the session and unbinds all the data bound to it. Even if the client's browser makes another request with the same session ID, the invalidated session is not used. Instead, a new session is created and the response contains the new session ID.

5. How to change the session id as soon as user logged in?

To prevent malicious attacks, it is always better to change session id as soon as user has logged in. This can be done by calling changeSessionId() on the request.