Servlet Session Tracking
HTTP is a "stateless" protocol, which means that each time the client retrieves a web page, the client opens a separate connection to the Web server, and the server automatically does not retain any record of previous client requests.
However, there are still the following three ways to maintain a session between the Web client and the Web server:
Cookies
A Web server can assign a unique session ID as a cookie for each Web client, and subsequent requests from the client can be identified using the received cookie.
This may not be an effective method because many browsers do not support cookies, so we recommend not using this approach to maintain a session.
Hidden Form Fields
A Web server can send a hidden HTML form field along with a unique session ID, as follows:
This entry means that when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time the Web browser sends back a request, the session_id value can be used to keep track of different Web browsers.
This may be an effective way to maintain session tracking, but clicking on a regular hypertext link () does not cause a form submission, so hidden form fields do not support regular session tracking either.
URL Rewriting
You can append some extra data to the end of each URL to identify the session, and the server will associate that session identifier with the stored data about the session.
For example, http://w3cschool.cc/file.htm;sessionid=12345, the session identifier is appended as sessionid=12345, and the identifier can be accessed by the Web server to identify the client.
URL rewriting is a better way to maintain a session; it works well when the browser does not support cookies, but its drawback is that every URL is dynamically generated to assign a session ID to the page, even in a very simple static HTML page.
The HttpSession Object
In addition to the three methods above, Servlets provide the HttpSession interface, which offers a way to identify users across multiple page requests or visits to a website and to store information about the user.
The Servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session lasts for a specified period of time, across multiple connections or page requests.
You can obtain the HttpSession object by calling the public method of HttpServletRequest getSession() as shown below:
HttpSession session = request.getSession();
You need to call this before sending any document content to the client request.getSession(). Several important methods available in the HttpSession object are summarized below:
| No. | Method & Description |
|---|---|
| 1 | public Object getAttribute(String name) |
| This method returns the object with the specified name in this session, or null if there is no object with that name. | |
| 2 | public Enumeration getAttributeNames() |
| This method returns an enumeration of String objects containing the names of all objects bound to this session. | |
| 3 | public long getCreationTime() |
| This method returns the time when this session was created, measured in milliseconds since midnight, January 1, 1970, GMT. | |
| 4 | public String getId() |
| This method returns a string containing the unique identifier assigned to this session. | |
| 5 | public long getLastAccessedTime() |
| This method returns the time when the client last sent a request associated with this session, measured in milliseconds since midnight, January 1, 1970, GMT. | |
| 6 | public int getMaxInactiveInterval() |
| This method returns the maximum time interval, in seconds, that the Servlet container keeps the session open when the client is inactive. | |
| 7 | public void invalidate() |
| This method invalidates this session and unbinds any objects bound to it. | |
| 8 | public boolean isNew() |
| This method returns true if the client does not yet know about this session, or if the client chooses not to participate in the session. | |
| 9 | public void removeAttribute(String name) |
| This method removes the object with the specified name from this session. | |
| 10 | **public void setAttribute(String name, Object value) ** |
| This method binds an object to this session using the specified name. | |
| 11 | public void setMaxInactiveInterval(int interval) |
| This method specifies the time between client requests, in seconds, before the Servlet container indicates the session is invalid. |
Session Tracking Example
This example shows how to use the HttpSession object to obtain the session creation time and last access time. If no session exists, we will create a new session through the request.
package com.runoob.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class SessionTrack
*/
@WebServlet("/SessionTrack")
public class SessionTrack extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// If no session exists, create a session object
HttpSession session = request.getSession(true);
// Get session creation time
Date createTime = new Date(session.getCreationTime());
// Get the last access time of this webpage
Date lastAccessTime = new Date(session.getLastAccessedTime());
//Set the date output format
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String title = "Servlet Session Example - Runoob Tutorial";
Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("Runoob");
if(session.getAttribute(visitCountKey) == null) {
session.setAttribute(visitCountKey, new Integer(0));
}
// Check if there are new visitors on the webpage
if (session.isNew()){
title = "Servlet Session Example - Runoob Tutorial";
session.setAttribute(userIDKey, userID);
} else {
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);
// Set response content type
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String docType = "\n";
out.println(docType +
"\n" +
"" + title + " \n" +
"\n" +
"" + title + "
\n" +
"Session 信息
\n" +
"\n" +
"\n" +
" Session 信息 值 \n" +
"\n" +
" id \n" +
" " + session.getId() + " \n" +
"\n" +
" 创建时间 \n" +
" " + df.format(createTime) +
" \n" +
"\n" +
" 最后访问时间 \n" +
" " + df.format(lastAccessTime) +
" \n" +
"\n" +
" 用户 ID \n" +
" " + userID +
" \n" +
"\n" +
" 访问统计: \n" +
" " + visitCount + " \n" +
"
\n" +
"");
}
}
Compile the Servlet above SessionTrack, and create the appropriate entry in the web.xml file.
SessionTrack
com.runoob.test.SessionTrack
SessionTrack
/TomcatTest/SessionTrack
Enter in the browser address bar http://localhost:8080/TomcatTest/SessionTrack, and the following result will be displayed when you run it for the first time:

Try running the same Servlet again, and it will display the following result:

Deleting Session Data
When you are finished with a user's session data, you have the following options:
- **Remove a specific attribute:** You can call public void removeAttribute(String name) method to delete the value associated with a specific key.
- **Delete the entire session:** You can call public void invalidate() method to discard the entire session.
- **Set the session expiration time:** You can call public void setMaxInactiveInterval(int interval) method to set the session timeout individually.
- **Log out the user:** If you are using a server that supports servlet 2.4, you can call logout to log out the client from the Web server and invalidate all sessions belonging to all users.
- **web.xml configuration:** If you are using Tomcat, in addition to the methods above, you can also configure the session timeout in the web.xml file, as follows:
15
The timeout in the example above is in minutes and will override Tomcat's default 30-minute timeout.
The getMaxInactiveInterval() method in a Servlet returns the session timeout in seconds. So, if the session timeout is configured in web.xml as 15 minutes, then getMaxInactiveInterval() will return 900.