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 the previous client request. any records.
But there are still the following three ways to maintain the session session between the Web client and the Web server:
Cookies
A web server can assign a unique session ID as a cookie to each web client, and subsequent requests from the client can be identified using the received cookie.
This may not be an efficient method because many browsers do not support cookies, so we recommend not using this method to maintain the session.
Hidden form fields
A web server can send a hidden HTML form field, along with a unique session ID, as follows:
<input type="hidden" name="sessionid" value="12345">
This entry means Then, when the form is submitted, the specified name and value are automatically included in the GET or POST data. The session_id value can be used to keep track of different web browsers each time the web browser sends back a request.
This may be an effective way to keep session track, but clicking a regular hypertext link (<A HREF...>) will not cause the form to submit, so neither will the hidden form fields. Supports regular session tracking.
URL Rewriting
You can append some additional data at the end of each URL to identify the session, and the server will correlate the session identifier with the stored data about the session. Union.
For example, http://w3cschool.cc/file.htm;sessionid=12345, the session 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 the session. It works well when the browser does not support cookies, but its disadvantage is that each URL is dynamically generated to assign to the page. A session session ID, even in very simple static HTML pages.
HttpSession Object
In addition to the above three methods, Servlet also provides the HttpSession interface, which provides a way to identify users and store information about users across multiple page requests or when accessing websites. The way.
The Servlet container uses this interface to create a session between an HTTP client and an HTTP server. A session lasts for a specified period of time and spans multiple connections or page requests.
You will get the HttpSession object by calling the public method getSession() of HttpServletRequest, as shown below:
HttpSession session = request.getSession();
You need to send any document content to the client before Call request.getSession(). The following summarizes several important methods available in the HttpSession object:
Serial number | Method & Description | ||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 | public Object getAttribute(String name ) This method returns the object with the specified name in the session, or null if there is no object with the specified name. | ||||||||||||||||||||||||
2 | public Enumeration getAttributeNames() This method returns the enumeration of the String object. The String object contains all the objects bound to the session The name of the session object. | ||||||||||||||||||||||||
3 | public long getCreationTime() This method returns the time when the session was created, since 1970 GMT Measured in milliseconds since midnight on January 1st. | ||||||||||||||||||||||||
4 | public String getId() This method returns a string containing the unique identifier assigned to the session. . | ||||||||||||||||||||||||
5 | public long getLastAccessedTime() This method returns the time when the client last sent a request related to the session. Measured in milliseconds since midnight GMT on January 1, 1970. | ||||||||||||||||||||||||
6 | public int getMaxInactiveInterval() This method returns the maximum time that the Servlet container keeps the session open when the client accesses it. Interval, in seconds. | ||||||||||||||||||||||||
7 | public void invalidate() This method indicates that the session is invalid and unbinds any object. | ||||||||||||||||||||||||
8 | public boolean isNew( If the client does not know the session yet, or if the client chooses not to participate in the session session, this method returns true | ||||||||||||||||||||||||
public void removeAttribute(String name)This method will remove the session from the session. Remove the object with the specified name. | |||||||||||||||||||||||||
public void setAttribute(String name, Object value) This method uses the specified The name binds an object to the session. | |||||||||||||||||||||||||
##public void setMaxInactiveInterval(int interval) | This method is in the Servlet container. Specifies the time, in seconds, between client requests before indicating that the session is invalid.Session tracking exampleThis example illustrates how to use the HttpSession object to obtain the session creation time and last access time. If the session does not exist, we will create a new one with the 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 above Servlet SessionTrack and create the appropriate entries in the web.xml file. Enter http://localhost:8080/SessionTrack in the browser address bar. When you run it for the first time, the following results will be displayed: Welcome to my websiteSession Information
Session Information
|