JSP Session

HTTP is a stateless protocol, which means that each time a client retrieves a web page, a separate server connection is opened, so the server does not log any information requested by the previous client.

There are three ways to maintain a client-server session:


The web server can specify a unique session ID as a cookie to represent each client to identify the next request from the client.

This may not be an effective way, because many times browsers do not necessarily support cookies, so we do not recommend using this method to maintain sessions.

Hide form fields

A web server can send a hidden HTML form field and a unique session ID, like this:

<input type="hidden" name="sessionid" value="12345">

This entry means that when the form is submitted, the specified name and value will be automatically included in the GET or POST data. Whenever a browser sends a request, the value of session_id can be used to save the trajectory of different browsers.

This way may be an effective way, but click <A HREF>Form submission events are not generated when a hyperlink is in the label, so hidden form fields do not support universal session tracking.

Rewrite URL

You can add some extra data after each URL to distinguish the session, and the server can associate the session identifier with this data.

For example, http://welookups.com/file.htm;sessionid=12345, session identifier is sessionid=12345, the server can use this data to identify the client.

In contrast, rewriting URLs is a better way to work even if the browser doesn't support cookies, but the downside is that you have to dynamically specify the session ID for each URL, even if it's a simple HTML page.

Session object

In addition to the above methods, JSP uses the HttpSession interface provided by the servlet to identify a user and store all access information of the user.

By default, JSP allows session tracking, and a new HttpSession object will be automatically instantiated for new clients. Disabling session tracking requires explicitly turning it off by setting the value of the session attribute in the page directive to false, like this:

<%@ page session="false" %>

The JSP engine exposes the implicit session object to the developer. Since the session object is provided, the developer can conveniently store or retrieve the data.

The following table lists some important methods of the session object:

S.N. Methods & Description
1 public Object getAttribute(String name)

Returns the object bound to the specified name in the session object, or null if it does not exist
2 public Enumeration getAttributeNames()

Returns all object names in the session object
3 public long getCreationTime()

Returns the time the session object was created, in milliseconds, from the early morning of January 1, 1970.
4 public String getId()

Returns the ID of the session object
5 public long getLastAccessedTime()

Returns the last time the client accessed, in milliseconds, from the early morning of January 1, 1970.
6 public int getMaxInactiveInterval()

Returns the maximum time interval in seconds during which the servlet container will keep the session open
7 public void invalidate()

Invalidate the session and unbind any objects bound to the session
8 public boolean isNew()

Returns whether it is a new client, or whether the client refuses to join the session
9 public void removeAttribute(String name)

Remove the object with the specified name in the session
10 public void setAttribute(String name, Object value) 

Generate an object with the specified name and value and bind to the session
11 public void setMaxInactiveInterval(int interval)

Used to specify the time, in seconds, the servlet container will keep the session valid for this period of time

JSP Session Application

This example describes how to use the HttpSession object to get the creation time and the last access time. We will associate a new session object with the request object if it does not already exist.

<%@ page language="java" contentType="text/html; charset=UTF-8"
<%@ page import="java.io.*,java.util.*" %>
   // Get the session creation time
   Date createTime = new Date(session.getCreationTime());
// Get the last time to visit the page   Date lastAccessTime = new Date(session.getLastAccessedTime());

   String title = "Visit the Visit the rookie tutorial example again tutorial example again";
   Integer visitCount = new Integer(0);
   String visitCountKey = new String("visitCount");
   String userIDKey = new String("userID");
   String userID = new String("ABCD");

   if (session.isNew()){
      title = "Visit the  tutorial example";
      session.setAttribute(userIDKey, userID);
      session.setAttribute(visitCountKey,  visitCount);
   } else {
       visitCount = (Integer)session.getAttribute(visitCountKey);
       visitCount += 1;
       userID = (String)session.getAttribute(userIDKey);
       session.setAttribute(visitCountKey,  visitCount);
<title>Session track</title>

<h1>Session track</h1>

<table border="1" align="center"> 
<tr bgcolor="#949494">
   <th>Session information</th>
   <td><% out.print( session.getId()); %></td>
   <td>Creation time</td>
   <td><% out.print(createTime); %></td>
   <td>Last access time</td>
   <td><% out.print(lastAccessTime); %></td>
   <td>user ID</td>
   <td><% out.print(userID); %></td>
   <td><% out.print(visitCount); %></td>