English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JSP Session

HTTP is a stateless protocol, which means that each time the client retrieves a web page, a separate server connection must be opened, so the server does not record any information about the previous client requests.

There are three methods to maintain the session between the client and the server:

    Cookies

The network server can specify a unique session ID as a cookie to represent each client, used to identify the client's subsequent requests.

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.

    Hidden form field

A network server can send a hidden HTML form field and a unique session ID, as shown below:

<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. Every time the browser sends a request, the value of session_id can be used to save the track of different browsers.

This may be an effective way, but when clicking on the hyperlink in the <A HREF> tag, no form submission event will be generated, so hidden form fields also do not support universal session tracking.

    URL rewriting

You can add some additional data at the end of each URL to distinguish sessions, and the server can associate the session identifier based on these data.

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

Compared to this, rewriting URLs is a better way, even if the browser does not support cookies, it can still work, but the disadvantage is that you must dynamically specify the session ID for each URL, even if it is a simple HTML page.

    Session object

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

By default, JSP allows session tracking, and a new HttpSession object will be automatically instantiated for a new client instance. To disable session tracking, it needs to be explicitly turned off by setting the session attribute value in the page directive to false, as shown below:

<%@ page session="false" %>

The JSP engine exposes the implicit session object to the developer. With the provision of the session object, developers can conveniently store or retrieve data.

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

S.N.Method & Description
                1public Object getAttribute(String name) Return the object bound to the specified name in the session object, or return null if it does not exist
                2public Enumeration getAttributeNames() Return all object names in the session object
                3public long getCreationTime() Return the creation time of the session object in milliseconds, from1970 years1month1Starting from midnight
                4public String getId() Return the ID of the session object
                5public long getLastAccessedTime() Return the time of the last access of the client in milliseconds, from1970 years1month1Starting from midnight
                6public int getMaxInactiveInterval() Return the maximum time interval in seconds, the servlet container will keep the session open during this period
                7public void invalidate() Invalidates the session, unbinding any objects bound to the session
                8public boolean isNew() Return whether it is a new client or if the client has refused to join the session
                9public void removeAttribute(String name) Remove the object with the specified name from the session
                10public void setAttribute(String name, Object value)  Use the specified name and value to create an object and bind it to the session
                11public void setMaxInactiveInterval(int interval) Used to specify the time in seconds, the servlet container will keep the session valid during this period

JSP Session Application

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

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*"%>
<%
   // Obtain the session creation time
   Date createTime = new Date(session.getCreationTime());
   // Obtain the time of the last visited page
   Date lastAccessTime = new Date(session.getLastAccessedTime());
   String title = "Revisit Basic Tutorial Website Example";
   Integer visitCount = new Integer(0);
   String visitCountKey = new String("visitCount");
   String userIDKey = new String("userID");
   String userID = new String("ABCD");
   // Detect if there is a new visitor to the web page
   if (session.isNew()) {
      title = "Visit Basic Tutorial Website 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);
   }
%>
<html>
<head>
<title>Session Tracking</title>
</head>
<body>
<h1>Session Tracking</h1>
<table border="1" align="center"> 
<tr bgcolor="#949494">
   <th>Session Information</th>
   <th>Value</th>
</tr> 
<tr>
   <td>ID</td>
   <td><% out.print(session.getId()); %></td>
</tr> 
<tr>
   <td>Create time</td>
   <td><% out.print(createTime); %></td>
</tr> 
<tr>
   <td>Last access time</td>
   <td><% out.print(lastAccessTime); %></td>
</tr> 
<tr>
   <td>User ID</td>
   <td><% out.print(userID); %></td>
</tr> 
<tr>
   <td>Number of visits</td>
   <td><% out.print(visitCount); %></td>
</tr> 
</table> 
</body>
</html>

Try to access http://localhost:8080/testjsp/main.jsp , the result when running for the first time will be as follows:

When you visit again, you will get the following result:

Delete Session Data

After processing a user's session data, you have the following options:

  • Remove a specific attribute:

    Call the public void removeAttribute(String name) method to remove the specified attribute.

  • Delete the entire session:

    Call the public void invalidate() method to invalidate the entire session.

  • Set session validity period:

    Call the public void setMaxInactiveInterval(int interval) method to set the session timeout.

  • Log out user:

    Supports servlet2.4Version of the server, you can call the logout() method to log out the user and invalidate all related sessions.

  • Configure the web.xml file:

    If you are using Tomcat, you can configure the web.xml file as follows:

  <session-config>
    <session-timeout>15</session-timeout>
  </session-config>

The timeout is in minutes, and the default timeout time in Tomcat is30 minutes.

The getMaxInactiveInterval() method in Servlet returns the timeout time in seconds. If the timeout is configured in web.xml as15If the maximum inactive interval is set to minutes, the getMaxInactiveInterval() method will return900.