Servlet Session tracking
HTTP is a “stateless” protocol, which means that every time a client retrieves a web page, the client opens a separate connection to the Web server, and the server automatically does not retain any records previously requested by the client.
However, there are still three ways to maintain a session session between a Web client and a Web server:
Hidden form fields
A Web server can send a hidden HTML form field, as well as a unique session
session ID, as follows:
<input type="hidden" name="sessionid" value="12345">
This entry means that when the form is submitted, the specified name and value are automatically included in the GET or POST data. Every time a Web browser sends back a request session_id
values can be used to keep track of different Web browsers.
This may be a way to maintain session
session tracking is an effective way, but clicking on a regular hypertext link (< A HREF… >) does not result in a form submission, so hidden form fields do not support regular session
session tracking.
URL rewriting
You can append some additional data to the end of each URL to identify the session session, and the server associates the session session identifier with the stored data about the session session.
For example, http://w3cschool.cc/file.htm;sessionid=12345, session session identifiers are appended as sessionid=12345
the identifier can be accessed by the Web server to identify the client.
URL rewriting is a better maintenance session
session mode, which workswell when the browser does not support cookie, but its disadvantage is thateach URL is dynamically generated to assign a session
session ID, evenin a very simple static HTML page.
HttpSession object
In addition to the three ways mentioned above, Servlet also provides HttpSession
interface, which provides a way to identify users and store information about users when requesting or visiting a Web site across multiple pages.
The Servlet container uses this interface to create a HTTP client and HTTP server session
conversation. The session lasts for a specified period of time and spans multiple connections or page requests.
You will call the HttpServletRequest
the public method of getSession()
to get HttpSession
object, as follows:
HttpSession session = request.getSession();
You need to call before sending any document content to the client request.getSession()
. The following is a summary HttpSession
thereare several important methods available in the
Serial number |
Method & description |
---|---|
1 |
Public Object getAttribute (String name) this method returns an object with the specified name in the session session, or null if there is no object with the specified name. |
2 |
Public Enumeration getAttributeNames () this method returns an enumeration of the String object, which contains the names of all objects bound to the session session. |
3 |
Public long getCreationTime () this method returns the time the session session was created, in milliseconds, from midnight on January 1, 1970 GMT. |
4 |
Public String getId () this method returns a string containing the unique identifier assigned to the session session. |
5 |
Public long getLastAccessedTime () this method returns the last time the client sent a request related to the session session from midnight on January 1, 1970 GMT, in milliseconds. |
6 |
Public int getMaxInactiveInterval () this method returns the maximum interval in seconds that the Servlet container keeps the session session open during client access. |
7 |
Public void invalidate () this method indicates that the session session is invalid and unbinds any objects on it. |
8 |
Public boolean isNew () this method returns true if the client does not already know about the session session, or if the customer chooses not to join the session session. |
9 |
Public void removeAttribute (String name) this method removes an object with the specified name from the session session. |
10 |
Public void setAttribute (String name, Object value) this method binds an object to the session session with the specified name. |
11 |
Public void setMaxInactiveInterval (int interval) this method specifies the time in seconds between client requests before the Servlet container indicates that the session session is invalid. |
Session trace instance
This example shows how to use the HttpSession
object acquisition session
session creation time and last access time. If it doesn’t exist,``session`` session, we will create a new session
conversation.
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 there is no session session, create a session object
HttpSession session = request.getSession(true);
// Get session creation time
Date createTime = new Date(session.getCreationTime());
// Get the last visit time of the webpage
Date lastAccessTime = new Date(session.getLastAccessedTime());
//Format date output
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String title = "Servlet Session Example - Rookie 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 - Rookie 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 = "<!DOCTYPE html>\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">Session information</h2>\n" +
"<table border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#949494\">\n" +
" <th>Session information</th><th>value</th></tr>\n" +
"<tr>\n" +
" <td>id</td>\n" +
" <td>" + session.getId() + "</td></tr>\n" +
"<tr>\n" +
" <td>Creation time</td>\n" +
" <td>" + df.format(createTime) +
" </td></tr>\n" +
"<tr>\n" +
" <td>Last Accessed Times</td>\n" +
" <td>" + df.format(lastAccessTime) +
" </td></tr>\n" +
"<tr>\n" +
" <td>user ID</td>\n" +
" <td>" + userID +
" </td></tr>\n" +
"<tr>\n" +
" <td>Access statistics:</td>\n" +
" <td>" + visitCount + "</td></tr>\n" +
"</table>\n" +
"</body></html>");
}
}
Compile the Servlet above SessionTrack
and in the web.xml
create the appropriate entry in the file.
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<!-- Class name -->
<servlet-name>SessionTrack</servlet-name>
<!-- The package it is in -->
<servlet-class>com.runoob.test.SessionTrack</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionTrack</servlet-name>
<!-- Visited website -->
<url-pattern>/TomcatTest/SessionTrack</url-pattern>
</servlet-mapping>
</web-app>
Enter http://localhost:8080/TomcatTest/SessionTrack in the browser address bar, and the following results will be displayed when you run it for the first time:
Try running the same Servlet again, and it will display the following result:
Delete Session session data
When you have completed a user’s session
for session data, you have thefollowing options:
Remove a specific property: you can call the
public void removeAttribute(String name)
method to delete the value associated with a specific key.Delete the entire
session
session: you can callpublic void invalidate()
method to discard the wholesession
conversation.Set up
session
session expiration time: you can callpublic void setMaxInactiveInterval(int interval)
method to set thesession
the session timed out.Log out of users: if you are using a server that supports servlet 2.4, you can call logout to log out the client of the Web server and set all the
session
the session is set to invalid.web.xml
configuration: if you are using Tomcat, in addition to the abovemethods, you can also use theweb.xml
configuration in Filsession
the session timed out, as follows:
<session-config>
<session-timeout>15</session-timeout>
</session-config>
The timeout in the above example is in minutes, which overrides the default timeout of 30 minutes in Tomcat.
In a Servlet getMaxInactiveInterval()
method returns the timeout, in seconds, for the session session. So, if you are in web.xml
if the session session timeout is configured as 15 minutes in the getMaxInactiveInterval()
will return 900.