Session Management in Java
This article is aimed to explain about session management in servlets using different techniques and with example programs.
What is a Session?
- A session is a period of time where the user sends multiple requests and receives multiple responses.
- If you are developing any web application then a client may send multiple requests with some information.
- The information sent by the client with one request will not be accessed in another request.
- Session means the duration when the client is accessing the application first time and when the client is leaving the application.
- If you want to access the data of one request into another request then you need to manage the SESSION.
- If you want to manage the SESSION in the WEB application, you have to do two things.
- Identify the client
- Manage the conversational state(Storing the client-specific information).
- To identify the client as new or old, the container will use Session id.
- To store clients conversational state or data. You have to use the HttpSession object.
HttpSession object will be created by the container when you call getSession() method the first time.
HttpSession session = request.getSession();
How Session works:
The basic concept of session, whenever a user starts using your application, we can save unique identification information about that, in an object until it destroyed. So wherever the user goes, we will always have his information and we can always manage which user is doing what. Whenever a user wants to exit from your application, destroy the object with his information.
Implementation inside the getSession() method:
class HttpServletRequestImpl implements HttpServletRequest
public HttpSession getSession()
- checks whether the incoming request contains the cookie with name JSESSIONID or not.
- If the incoming request contains the Cookie with name JSESSIONID then collects the value of the cookie which is Session id and picks the session object related to session id.
- If the incoming request does not contain the cookie with name JSESSIONID then following steps with happen:-
- create a session object. HttpSession session= request.getSession();
- Generates a unique session id. String id= <Hexadecimal_OF_ClientIPADD>+<Hexadecimal_OF_CurrentTimeStamp>+<Hexadecimal_OF_ServletTimeStamp>;
- stores the session id in session object. Session.setId(id);
- create the cookie with the name JSESSIONIDCookies c = new Cookies(“JSESSIONID”, id);
- Adds the cookie to the response object.Res.addCookie(c);
- Returns the Session object
There are 4 session management techniques and they are listed below:
- Hidden Fields
You can use the following to store the client’s conversational data.
You can use the following to carry the Session-Id.
- Hidden fields
- HttpSession is an interface available in a Javax.servlet.HTTP package
- you can get the HttpSession object with the following methods of HttpservletRequest.
- HttpSession getsession();
- HttpSession getSession(boolean)
If the boolean value is true:-
HttpSession s =req.getSession(true); then following things will happen.
if(session object available) then
create a new session object and return
If the boolean value is false as:-
HttpSession s = req.getSession(false); then following thing will happen:
if(session object available) then
You can store and access the user-specific data in HttpSession object as an attribute with the following methods:
- void setAttribute(String Object)
- Object getAttribute(String)
- void removeAttributes(String)
- Enumeration getAttributeNames()
You can also use the following 4 methods that are deprecated.
- Void putvalue(String, Object)
- Object getValue(String)
- void removeValue(String)
- String getValueNames()
You can destroy the HttpSession object by calling invalidate() method:
Q1. How can i check whether session object returned by getSession() is old or new?
Ans: Using boolean is new() method.
Q2. How can I get the session associated with the session object?
Ans: using getId() method.
Q3. How can I get the session creation time?
Ans: using getCreationTime() method.
Q4. How can I find the Session available?
Ans: using getSession(false);
By calculating the time difference between session creation time and a current time.
Q5. How can I access when the session was accessed last time?
Ans: using getLastAccessedTime();
Q6. How can I specify the idle timeout (or) inactive interval?
Ans: you can specify the idle timeout in two ways:
- setMaxInactiveInterval(int) in terms of seconds
- specify the following tags in web.xml<session-config><session-timeout>5</session-timeout><session-config>// interms of min
Q7. Can i access the Servletcontext with session.
Ans: Yes, you can with the following method: ServletContext getServletContext();
- A session will be created newly when you call getSession() method the first time.
- In every JSP, by default getSession() will be called. ie. When you request for any JSP then session object will be created automatically without your calling the getSession() method.
- If you want you can disable the automatic session creation by specifying the following tag:
<%@ page session=”false” %>
- Cookies is a class available in a javax.servlet.HTTP package.
- Cookies are simple information with name and value.
- Normally cookie’s will be created at server machine and persist at a client machine.
- Cookies created at server machine will come to the client machine and persist at the client machine,
- Cookies persistent at client machine will go to server machine along with HttpRequested.
Exploring Cookies Explanation:-
- Creating cookies: Cookies ck= new Cookies(“email”, firstname.lastname@example.org);
- Adding cookies to response: response.addCookie(ck);
- Accessing cookies from request:
Cookies ck = request.getCookies();for(Cookies c:ck);String cn= c.getName();String cv= c.getValue();System.out.println(“cn+ “ ”+ cv);}
Q) How can i specify the expiry time for cookies?
Ans: using setMaxAge() method;
URL-Rewriting and Hidden Fields
- The container uses Session id to identify the client as old or new.
- Container send the session id to the client machine with the cookies with name JSESSIONID
- Sometimes, you may get problems with cookies.
- When your browser is not supporting the cookies.
- When the client deletes the cookies.
- When any problem happens to cookies then request will not carry the cookie with name JSESSIONID
- if a request is coming without JSESSIONID cookies then the container will treat that client as new and provides the new session object and new session id i.e, Client is losing the previous session,
Object and conversational data available in that session object.
You can use URL-Rewriting or hidden fields to carry the session id from client to server and from server to client.
- URL_Rewritng is the process of attaching the session id to the URL. It is also called the encoding the URL.
- To encode the URL, use the following.
- response.encodeURL(“ …”);
- encodeUrl() method takes the URL as a parameter and it will generate the following URL after encoding.
- You can store the session id in the hidden fields as follows.<input type=”hidden” name=”JSESSIONID” value=”<%=session.getId()%>”
- when you are developing any web application using Struts, JSP, Spring MVC frameworks then you no need to implement URL-Rewriting concept. These frameworks have inbuilt support for it.
The use of session management is an important design issue because of the complexity of today’s Web sites. As Java developers, we have access to a powerful and robust session manager through the use of the HttpSession API. Learning all of Java’s session management features will make your job as a Web developer easier and help you create a better experience for your Web site visitors. That’s all for session management in java servlets, we will look into Servlet Filters and Listeners in future articles. Please, feel free to drop a comment in the below comment box, if you find any doubt in the topic or you want to share more information about the topic. Happy Learning!
READ NOW :- Some Unknown Facts About Java Servlet Filter
Java Developer with 4.5 years of software development experience in development and deployment of Internet Of Things (IOT) based web Applications and Enterprise Application using java and J2EE Technologies.