Managing Session using Session Objects

Sessions are represented by an HttpSession object. We access a session by calling the request.getSession() or request.getSession(boolean) method of a HttpServletRequest object named ‘request‘. This method returns the current session associated with this request, or, if the request does not have a session, it creates one (unless boolean argument is false). All the example codes are placed within SessionTest directory under webapps. See some coding examples below.

 

Case I: To Determine whether the Session is New or Old

In this program we are going to make one Servlet on session in which we will check whether the session is new or old. To make this program firstly we need to make one class named CheckingTheSession.  Inside the doGet() method, which takes two objects one of request and second of response. Inside this method call the method getWriter() of the response object. Use getSession() of the request object, which returns the HttpSession object. Now by using the HttpSession we can find out whether the session is new or old. 

The code of the program is given below:

CheckingTheSession.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CheckingTheSession extends HttpServlet {

public void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

PrintWriter pw = response.getWriter();
pw.println("Checking whether the session is new or old");

HttpSession session = request.getSession(); //creating session object

if(session.isNew()) {
pw.println("You have created a new session");
}
else {
pw.println("Session already exists");
}
}

//for "HTTP GET" method
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

//for "HTTP POST" method
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}

 

The first run of the program is given below:

 

On requesting the Servlet next time will produce the following output:

 

 

Case II: To Determine a Pre-existing Session

In this example we are going to find out whether the session is pre-existing or not. Consider a situation where servlet want to use only a existing session. It is not always a good idea to create a new session. To perform this work we have one overloaded method getSession(boolean) of the request object. If we don’t want to create a new session then we should use getSession(false). In the example below we have used this method which will test whether the session is null or not. If there is no session then the new session will be created by the method getSession().

The code of the program is given below:

PreExistingSession.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class PreExistingSession extends HttpServlet {

public void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

PrintWriter pw = response.getWriter();
pw.println("Testing The Session : ");

HttpSession session = request.getSession(false);

if(session==null) {
pw.println("There is no session");
pw.println("Can we create a session for you. Creating.........");
session = request.getSession();
}
else {
pw.println("Session already exists");
}
}

//for "HTTP GET" method
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

//for "HTTP POST" method
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}

 

The first run of the program is given below: 

 

 

 

 

 

 

 

On requesting the Servlet next time will produce the following output:

 

 

Case III: Displaying Session Values using Servlet

Sometime while developing web application it is necessary to interact with the different values of the Session object. In this example we will explore the different values of the Session object and then learn how to use it in our programming code.

We will learn how to find all the session related information like:

  • getId(). This method is used to find the identifier of the session which is unique.
  • isNew(). This method is used when find, whether session is newly created or preexisted. If session has never seen by user then this method return “true” but if session is preexisted then it return “false”.
  • getCreationTime(). This method is used to find the creation time of session. To use of this method we can find the following details about session i.e. day, month, date, time, GMT (Greenwich Mean Time) and year will be displayed.
  • getLastAccessedTime(). This method is used to find the last accessed time of session. It returns the time, in milliseconds.
  • getMaxInactiveInterval(). This method returns the total time, in seconds, during which session remains active if user does not accesses the session for this maximum time interval. After this time the session will be invalidated automatically. A negative value indicates that the session should never timeout.

The code of the program is given below:

HttpSessionDisplay.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class HttpSessionDisplay extends HttpServlet {
String head;

public void processRequest(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {

HttpSession session = request.getSession(true); //creating session object
PrintWriter out = response.getWriter();
Integer count = new Integer(0);

if (session.isNew()) {
head = "New Session Value";
}
else {
head = "Old Session value";
Integer oldcount =(Integer)session.getValue("count");
if (oldcount != null) {
count = new Integer(oldcount.intValue() + 1);
}
}

session.putValue("count", count);
out.println("<HTML><BODY BGCOLOR=\"white\">\n" +
"<H2 ALIGN=\"CENTER\">" + head + "</H2>\n" +
"<H3 ALIGN=\"CENTER\">Description about Session:</H3>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"gray\">\n" +
" <TH>Information Type<TH>Session Value\n" +"<TR>\n" +" <TD>ID\n" +
"<TD>" + session.getId() + "\n" +
"<TR>\n" + " <TD>Session Creation Time\n" +
" <TD>" + new Date(session.getCreationTime()) + "\n" +
"<TR>\n" +" <TD>Last Session Access Time\n" +" <TD>" +
new Date(session.getLastAccessedTime()) + "\n" +
"<TR>\n" +" <TD>Number of Previous Session Accesses\n" +
"<TD>" + count + "\n" +
"</TABLE>\n" +"</BODY></HTML>");

}

//for "HTTP GET" method
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

//for "HTTP POST" method
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

}

 

The first run of the program is given below: 

 

 

 

 

 

 

 

 

 

On requesting the Servlet next time will produce the following output:

 

 

 
The web.xml file for all these programs together:
<web-app>
<servlet>
<servlet-name>Test1</servlet-name>
<servlet-class>CheckingTheSession</servlet-class>
</servlet>
<servlet>
<servlet-name>Test2</servlet-name>
<servlet-class>PreExistingSession</servlet-class>
</servlet>
<servlet>
<servlet-name>Test3</servlet-name>
<servlet-class>HttpSessionDisplay</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test1</servlet-name>
<url-pattern>/check1.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Test2</servlet-name>
<url-pattern>/check2.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Test3</servlet-name>
<url-pattern>/check3.do</url-pattern>
</servlet-mapping>
</web-app>