Latest web development tutorials

Servlet Session Tracking

HTTP is a "stateless" protocol, which means that every time the client retrieves the pages, the client opens a separate connection to the Web server, the server does not automatically record before any client requests are reserved.

But there are still three ways to maintain session conversation between the Web client and the Web server:

Cookies

A Web server can be assigned a unique session ID as the session for each Web client cookie, subsequent requests for the client can be used to identify the received cookie.

This may not be an effective method, because many browsers do not support cookie, so we do not recommend using this way to maintain session session.

Hidden form fields

A Web server can send a hidden HTML form fields, 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 will be automatically included in GET or POST data. Every time when the Web browser sends back the request, session_id value can be used to keep different Web browser tracking.

This may be an effective way to maintain session session tracking, but click on the Conventional hypertext link (<A HREF...>) does not lead to a form submission, so the hidden form fields do not support regular session session tracking.

URL Rewriting

You can append some extra data on each end of the URL to identify the session session session session identifier and the data stored session about session associated server will.

For example, http: //w3cschool.cc/file.htm; sessionid = 12345, session session identifier is attached as sessionid = 12345, an identifier can be accessed the Web server to identify the client.

URL rewriting is a better way to maintain session session, it can work very well when the browser does not support cookie, but its drawback is dynamically generated for each URL to assign a session ID for the session page, even if is very simple static HTML pages will be, too.

HttpSession objects

In addition to the above three ways, Servlet also provides the HttpSession interface, which provides the user to identify and store information about the user when a cross more than one page request or visit manner.

Servlet container to use this interface to create a session conversation between an HTTP client and HTTP server. Session lasts a specified period of time, across multiple page requests or connections.

You will come to get HttpSession object by calling the HttpServletRequest Public methodgetSession (), as follows:

HttpSession session = request.getSession ();

You need before sending any document content to the client callsrequest.getSession ().Here is a summary of several important methods HttpSession objects are available:

序号方法 & 描述
1public Object getAttribute(String name)
该方法返回在该 session 会话中具有指定名称的对象,如果没有指定名称的对象,则返回 null。
2public Enumeration getAttributeNames()
该方法返回 String 对象的枚举,String 对象包含所有绑定到该 session 会话的对象的名称。
3public long getCreationTime()
该方法返回该 session 会话被创建的时间,自格林尼治标准时间 1970 年 1 月 1 日午夜算起,以毫秒为单位。
4public String getId()
该方法返回一个包含分配给该 session 会话的唯一标识符的字符串。
5public long getLastAccessedTime()
该方法返回客户端最后一次发送与该 session 会话相关的请求的时间自格林尼治标准时间 1970 年 1 月 1 日午夜算起,以毫秒为单位。
6public int getMaxInactiveInterval()
该方法返回 Servlet 容器在客户端访问时保持 session 会话打开的最大时间间隔,以秒为单位。
7public void invalidate()
该方法指示该 session 会话无效,并解除绑定到它上面的任何对象。
8public boolean isNew()
如果客户端还不知道该 session 会话,或者如果客户选择不参入该 session 会话,则该方法返回 true。
9public void removeAttribute(String name)
该方法将从该 session 会话移除指定名称的对象。
10public void setAttribute(String name, Object value)
该方法使用指定的名称绑定一个对象到该 session 会话。
11public void setMaxInactiveInterval(int interval)
该方法在 Servlet 容器指示该 session 会话无效之前,指定客户端请求之间的时间,以秒为单位。

Session Tracking Examples

This example shows how to use the HttpSession object to obtain session session creation time and last access time. If there is no session session, we will create a new session by session requests.

package com.w3big.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
	{
		// 如果不存在 session 会话,则创建一个 session 对象
		HttpSession session = request.getSession(true);
		// 获取 session 创建时间
		Date createTime = new Date(session.getCreationTime());
		// 获取该网页的最后一次访问时间
		Date lastAccessTime = new Date(session.getLastAccessedTime());
		 
	    //设置日期输出的格式  
	    SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
	
		String title = "Servlet Session 实例 - 本教程";
		Integer visitCount = new Integer(0);
		String visitCountKey = new String("visitCount");
		String userIDKey = new String("userID");
		String userID = new String("w3big");
	
		// 检查网页上是否有新的访问者
		if (session.isNew()){
			title = "Servlet Session 实例 - 本教程";
		 	session.setAttribute(userIDKey, userID);
		} else {
		 	visitCount = (Integer)session.getAttribute(visitCountKey);
		 	visitCount = visitCount + 1;
		 	userID = (String)session.getAttribute(userIDKey);
		}
		session.setAttribute(visitCountKey,  visitCount);
	
		// 设置响应内容类型
		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 信息</h2>\n" +
		        "<table border=\"1\" align=\"center\">\n" +
		        "<tr bgcolor=\"#949494\">\n" +
		        "  <th>Session 信息</th><th>值</th></tr>\n" +
		        "<tr>\n" +
		        "  <td>id</td>\n" +
		        "  <td>" + session.getId() + "</td></tr>\n" +
		        "<tr>\n" +
		        "  <td>创建时间</td>\n" +
		        "  <td>" +  df.format(createTime) + 
		        "  </td></tr>\n" +
		        "<tr>\n" +
		        "  <td>最后访问时间</td>\n" +
		        "  <td>" + df.format(lastAccessTime) + 
		        "  </td></tr>\n" +
		        "<tr>\n" +
		        "  <td>用户 ID</td>\n" +
		        "  <td>" + userID + 
		        "  </td></tr>\n" +
		        "<tr>\n" +
		        "  <td>访问统计:</td>\n" +
		        "  <td>" + visitCount + "</td></tr>\n" +
		        "</table>\n" +
		        "</body></html>"); 
	}
}

Compile the previousServlet SessionTrack, and create the appropriate entry in the web.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet> 
    <!-- 类名 -->  
    <servlet-name>SessionTrack</servlet-name>
    <!-- 所在的包 -->
    <servlet-class>com.w3big.test.SessionTrack</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>SessionTrack</servlet-name>
    <!-- 访问的网址 -->
    <url-pattern>/TomcatTest/SessionTrack</url-pattern>
  </servlet-mapping>
</web-app>

In the browser address bar, enterhttp: // localhost: 8080 / TomcatTest/ SessionTrack, when you first run the show the following results:

Try to run the same Servlet again, it will show the following results:


Delete Session session data

When you have finished a session user session data, you have the following options:

  • Remove a specific attribute: You can call thepublic void removeAttribute (String name)method to remove a specific value associated with a key.
  • Delete the entire session session: You can call thepublic void invalidate ()method to discard the entire session session.
  • Session set session expiration time: You can call thepublic void setMaxInactiveInterval (int interval)method to set up a separate session session timeout.
  • Logout Users: If youare using a supported servlet 2.4 server, you can call thelogoutto logout Web server client, and all users belonging to all session session as invalid.
  • web.xml configuration: If you are using Tomcat, in addition to the above methods, you can configure the session session timeout in web.xml file, as follows:
  <session-config>
    <session-timeout>15</session-timeout>
  </session-config>

Examples of the above-out time is minutes, Tomcat will override the default 30-minute timeout.

getMaxInactiveInterval in a Servlet in () method returns the timeout session session, in seconds. So, if configured session timeout in web.xml session time of 15 minutes, then getMaxInactiveInterval () will return 900.