In this tutorial you will introduced with the Servlet Session and its methods
Introduction To Servlet Session
A servlet session is a way to identify the user on the website. Servlet provides HttpSession interface which create an manages the session. At first you need to create the session object explicitly after checking neccessary information of the user for the validation of the user. And this session object is used to identify the user on the every servlet. when user wishes to logoff from the website then you need to destroy this session object. The HttpSession interface provides the many methods to do such type of work. The description of the methods and how to use them in application is given below.
Creating A Session
HttpSession session=request.getSession(true); or HttpSession session=request.getSession();
the getSession method may have boolean value either true or false or it may be empty. The getSession(true) and getSession() method have the same meaning. Both the methods creates a new session.
The getSession(false) indicates that you are not creating any new session.
Adding And Getting Attributes to the Session object
It is a good approach to identify the user from his session attributes. For this you need to add some user specific information in session object in name value pair. For example-
session.setAttribute("UserName", JSESSIONID);. Then you need to check this name name value pare before every visit of the servlet by using session.getAttribute("UserName");.
Destroying a Session Object
To destroy a session object you need to call session.invalidate() or session.setMaxInactiveInterval(0); this destroy the session.
Some Other Methods
getId() is used to getting a unique Session Id of the session object.
getCreationTime() this returns the time when session was created in millisecond /month/GMT etc.
getLastAccessedTime() this returns the last time when user sent a request for this session.
getServletContext() This returns the servlet context to which sesion belongs.
isNew() this method is used to check whether the session is new or not. If session is new then it returns the true value else it returns false.
removeAttribute("name") This removes the particular attribute from the session identified by its name.