Advertisement



< Prev
Next >



Session management by HttpSession



In this article, we are going to understand how to maintain a session by using an HttpSession object. Using an object of HttpSession interface, web container can locate if there an existing session associated with the user and if it doesn't find an existing session, it creates one.

This HttpSession object helps in storing a user information or a session data, to maintain its session and differentiate it from other users. The new session exists for a certain interval and it survives even when different requests are made by the same user.




Methods of HttpServletRequest used to create a new session


Method Description
void getSession() This method returns an existing session associated with the request or it creates a new session by returning an object of HttpSession (if it is unable to locate a session associated with the request).
void getSession(boolean)
  • Passing true to this method, it returns the existing session associated with the user or it creates a new session by returning an object of HttpSession(if it is unable to locate a session associated with the request).

  • Passing false to this method, it returns the existing session associated with the user or it returns a null(if it is unable to locate a session associated with the request).





Some useful methods available to session object.


The methods in the table below are part of javax.servlet.http.HttpSession interface. Hence, these methods are available to the JSP implicit session object, which is a type of HttpSession.

Methods Description
void setAttribute(String name, Object value) This method sets an object with a name in a session.
Object getAttribute(String name This method gets an object stored in a session with a name, or null.
void removeAttribute(String name) This method removes an object with a name from the session.
long getLastAccessedTime() This method returns the last time(since midnight Jan 1, 1970 in milliseconds) since a client accessed this session.
int getMaxInactiveInterval() This method gets the time(in seconds) before servlet contained invalidates the session.
void setMaxInactiveInterval(int seconds This method sets the time between client requests before the servlet container invalidates the session.
long getCreationTime() This method gets the creation time of the current session, since 1970 in milliseconds.
ServletContext getServletContext() This method returns the ServletContext to the current session.
boolean isNew() This method gives a true if the current session is new and client doesn't know about it.



Advertisement




Maintaining a Session within a Servlet


We are creating a Servlet extending the HttpServlet abstract class. HttpServlet class extends GenericServlet abstract class. This class named MyServlet1.java, implements doGet() method of HttpServlet class to handle the default get request made by the client after executing the this Servlet.


This Servlet does the following tasks -
MyServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class MyServlet1 extends HttpServlet
{

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

//Creates a variable to count the number of visits of the user
int counter = 0;

//Creates a session object
HttpSession session = request.getSession(true);

out.println("<b> Welcome, </b> " );
out.println("<br/>  <br/>   <br/> ");


boolean sessionInfo = session.isNew();	
out.println("Is this a new session = " + sessionInfo);
out.println("<br/> ");
out.println("Session ID = " + session.getId());
out.println("<br/> ");
out.println("This session was created = " + new Date(session.getCreationTime()));
out.println("<br/> ");
out.println("Last time when this session was accessed = " + new Date(session.getLastAccessedTime()));
out.println("<br/> ");
out.println("Maximum time for which this session can be inactive = " + session.getMaxInactiveInterval() + " seconds");
out.println("<br/>  <br/>  <br/> ");




if(sessionInfo)
{
	
	session.setAttribute("visit", counter);
	counter = counter + 1;
	out.println("<b> This is your first visit to this website </b>");
}
else 
{
	
	counter = (int)session.getAttribute("visit");
	counter = counter + 1;
	out.println("<b> Number of times you have visited this website : <b> "+ counter);
}

session.setAttribute("visit", counter);


}
}





Directory Structure of Servlet files




The diagram above depicts how to arrange the Servlet files in a specific directory structure, as per Java Servlet Specification-






Creating the Deployment Descriptor file


As per the Java Servlet specifications, every web application based on Servlet must have a Deployment Descriptor file(an XML file) named web.xml. So, let's create one -


web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0"
  metadata-complete="true">

  <display-name>Welcome tomcat</display-name>
  <description>
     Welcome tomcat
  </description>

  
<servlet>
 	<servlet-name>FirstServlet</servlet-name>
	<servlet-class>MyServlet1</servlet-class>
</servlet>



<servlet-mapping>
	<servlet-name>FirstServlet</servlet-name>
	<url-pattern>/Serv1</url-pattern>
</servlet-mapping>


</web-app>


In deployment descriptor file, <servlet> has two child tags <servlet-name> and <servlet-class> :






Note


The child tag <servlet-name> of <servlet> tag is matched with the <servlet-name> child tag of <servlet-mapping>. The <url-pattern> child tag is used to specify the URL to access Servlet, Hence -




Setting the classpath


Much of the support for developing the web applications based on the Java Servlet technology does not come with the core Java. Hence, in order to compile the Servlet programs, we have to set the classpath to a jar file named servlet-api.jar.

This jar file provides all the classes that are required for the Servlet programming and it comes within the lib Folder of Tomcat installation folder.

For example, in our case we have installed Tomcat Web Server within the C: Drive, hence the path to our lib folder containing the servlet-api.jar is - C:\apache-tomcat-9.0.2\lib

There are two ways to set the classpath -




Compiling the Servlet class


After setting the classpath, you need to compile the both of the Servlet class by entering the command at the folder where you've stored the Servlet class file.

javac -d WEB-INF/classes MyServlet1.java





Executing the Servlet


Executing the webpage containing the Servlet for the first time gives us the information about the new session created. This page also gives us a personalised welcome message on our first visit. This Servlet also maintains a counter which displays the number of times a user has visited this webpage.




On refreshing this webpage the Servlet gives us current value of the counter i.e. the number of times we have visited this webpage and the information about the current session. This counter is maintained by creating an HttpSession object






Please share this article -




< Prev
Next >
< Cookies in Servlet
Filters >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement

Notifications



Please check our latest addition

PYTHON


Advertisement