Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Servlet Session tracking


May 14, 2021 Servlet


Table of contents


Servlet Session tracking

HTTP is a "stateless" protocol, which means that each time a client retrieves a Web page, the client opens a separate connection to the Web server, which 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:

Cookies

A web server can assign a unique session session ID as a cookie for each web client, which can be identified by the received cookie for subsequent requests from the client.

This may not be an effective approach, as many browsers do not support cookies, so we recommend that you do not use this method to maintain a session session.

Hidden form fields

A Web server can send a hidden HTML form field, along with 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. Each time a web browser sends a request back, session_id value can be used to keep track of different web browsers.

This may be an effective way to keep session sessions tracked, but click on the regular hyper-text link. Form submission is not caused, so hidden form fields do not support regular session session tracking.

THE URL is override

You can append some additional data at the end of each URL to identify the session session, and the server associates the session session identifier with stored data about the session session.

For example, http://w3cschool.cn/file.htm; the sessionid is 12345, and the session session identifier is attached to the 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 session, and it works well when the browser does not support cookies, but the disadvantage is that each URL is dynamically generated to assign a session session ID to the page, even in a very simple static HTML page.

HttpSession object

In addition to the three ways above, Servlet provides an HttpSession interface that provides a way to identify users and store information about them when requesting or visiting a Web site across multiple pages.

The servlet container uses this interface to create a session session between an HTTP client and an HTTP server. The session lasts a specified period of time and spans multiple connections or page requests.

You'll get the HttpSession object by calling the public method getSession() of httpservletRequest, as follows:

HttpSession session = request.getSession();

You need to call request.getSession() before sending any document content to the client. Here's a summary of some of the important methods available in httpSession objects:

Serial number Method & Description
1 public Object getAttribute(String name)
This method returns an object with the specified name in the session session, and NULL is returned if the object is specified.
2 public Enumeration getAttributeNames()
This method returns the enumeration of the String object, and the String object contains all the names of the object bound to the session session.
3 public long getCreationTime()
The method returns the time created by the session session, and since the GRB is 20 midnight on January 1, 1970, in milliseconds.
4 public String getId()
This method returns a string containing a unique identifier assigned to the session session.
5 public long getLastAccessedTime()
This method returns the last time the client sends the request to the session session from the GMT time from Midnight, January 1, 1970, in milliseconds.
6 public int getMaxInactiveInterval()
This method returns the maximum time interval to be opened when the Servlet container keeps the session session when accessible, in seconds.
7 public void invalidate()
This method indicates that the session session is invalid and unlocks any object bound to it.
8 public boolean isNew(
If the client doesn't know the session session, or if the customer chooses not to participate in the session session, the method returns True.
9 public void removeAttribute(String name)
This method will remove the target of the specified name from the session session.
10 public void setAttribute(String name, Object value)
This method binds an object to the session session using the specified name.
11 public void setMaxInactiveInterval(int interval)
The method specifies the time between the client request before the Servlet container is invalid, and in seconds.

Session tracks instances

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

// 导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
 
// 扩展 HttpServlet 类
public class SessionTrack extends HttpServlet {
 
  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());

      String title = "欢迎回到我的网站";
      Integer visitCount = new Integer(0);
      String visitCountKey = new String("visitCount");
      String userIDKey = new String("userID");
      String userID = new String("ABCD");

      // 检查网页上是否有新的访问者
      if (session.isNew()){
         title = "欢迎来到我的网站";
         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");
      PrintWriter out = response.getWriter();

      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +       "transitional//en\">\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>Creation Time</td>\n" +
                "  <td>" + createTime + 
                "  </td></tr>\n" +
                "<tr>\n" +
                "  <td>Time of Last Access</td>\n" +
                "  <td>" + lastAccessTime + 
                "  </td></tr>\n" +
                "<tr>\n" +
                "  <td>User ID</td>\n" +
                "  <td>" + userID + 
                "  </td></tr>\n" +
                "<tr>\n" +
                "  <td>Number of visits</td>\n" +
                "  <td>" + visitCount + "</td></tr>\n" +
                "</table>\n" +
                "</body></html>");
  }
}

Compile the Servlet SessionTrack above and create the appropriate entry .xml the web server file. Enter a button in the browser http://localhost:8080/SessionTrack and the following results will appear when you first run it:

Welcome to my website

Session information

Session information Value
Id 0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time Tue Jun 08 17:26:40 GMT+04:00 2014
Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2014
User ID Abcd
Number of visits 0

Try running the same servlet again, and it will show the following results:

Welcome back to my website

Session information

Session information Value
Id 0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time Tue Jun 08 17:26:40 GMT+04:00 2014
Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2014
User ID Abcd
Number of visits 1

Delete Session session data

When you complete a user's session session data, you have several options:

  • Remove a specific property: You can call the public void removeAttribute method to remove the value associated with a particular key. to delete the value associated with a particular key.
  • Delete the entire session session: You can call the public void invalidate() method to discard the entire session session.
  • Set the session session expiration time: You can call the public void setMaxInactive International method to set the session session timeout separately.
  • Sign out of the user: 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 session sessions that belong to all users to invalid.
  • Web .xml configuration: If you are using Tomcat, in addition to the above method, you can configure the session session timeout in the web .xml file, as follows:
  <session-config>
    <session-timeout>15</session-timeout>
  </session-config>

The timeout in the instance above is in minutes and overrides the default 30-minute timeout in Tomcat.

The getMaxInactiveInterval() method in a servlet returns a timeout, in seconds, for the session session. Therefore, if you.xml configure the session session timeout time of 15 minutes in the web game, getMaxInactiveInterval() returns 900.