Servlets 简明教程

Servlets - Session Tracking

HTTP 是一种“无状态”协议,这意味着每次客户端检索网页时,客户端都会打开与 Web 服务器的独立连接,该服务器不会自动保留以前客户端请求的任何记录。

仍然有以下三种方法来维持 Web 客户端与 Web 服务器之间的会话:

Cookies

Web 服务器可以为每个网络客户端分配一个作为 cookie 的唯一会话 ID,并且在接收到 cookie 后,可用于识别客户的后续请求。

这可能不是一个有效的方法,因为很多时候浏览器不支持 cookie,因此我建议不要使用这些步骤来维护会话。

Hidden Form Fields

Web 服务器可以结合唯一会话 ID 发送隐藏的 HTML 表单字段,如下所示:

<input type = "hidden" name = "sessionid" value = "12345">

此条目表示,提交表单时,指定的名称和值将自动包含在 GET 或 POST 数据中。每次 Web 浏览器发送请求时,都可以使用 session_id 值来跟踪不同的 Web 浏览器。

这可能是跟踪会话的有效方法,但单击常规(<A HREF…​>)超文本链接不会导致表单提交,因此隐藏表单字段也不能支持常规会话跟踪。

URL Rewriting

你可以在每个 URL 的末尾附加一些额外的数据来标识会话,并且服务器可以将该会话标识符与它存储的有关该会话的数据相关联。

例如,对于 [role="bare"] [role="bare"]http://tutorialspoint.com/file.htm;sessionid = 12345,会话标识符附加为 sessionid = 12345,可从 Web 服务器访问以识别客户端。

URL 重写是维护会话的更好方法,即使浏览器不支持 cookie,它也能发挥作用。URL 重写的缺点是即使对于简单的静态 HTML 页面,你也必须动态生成每个 URL 以分配会话 ID。

The HttpSession Object

除了上述三种方法外,servlet 还提供了 HttpSession Interface,它提供了一种跨多个页面请求或访问网站识别用户并存储有关该用户信息的方法。

servlet 容器使用此接口来创建 HTTP 客户端与 HTTP 服务器之间的会话。会话会在一个指定的时间段内保持,跨多个来自用户的连接或页面请求。

你可以通过调用 HttpServletRequest 的公共方法 getSession() 来获取 HttpSession 对象,如下所示:

HttpSession session = request.getSession();

在向客户端发送任何文档内容之前,你需要调用 request.getSession()。以下是通过 HttpSession 对象可用的重要方法的摘要:

Sr.No.

Method & Description

1

*public Object getAttribute(String name)*此方法返回与此会话中指定名称绑定的对象,如果没有以该名称绑定对象,则返回 null。

2

public Enumeration getAttributeNames() 此方法返回一个 String 对象的枚举,其中包含绑定到此会话的所有对象的名称。

3

*public long getCreationTime()*此方法返回创建此会话的时间,以自 1970 年 1 月 1 日午夜 GMT 以来经过的毫秒数来衡量。

4

*public String getId()*此方法返回一个包含分配给此会话的唯一标识符的字符串。

5

*public long getLastAccessedTime()*此方法返回会话的最后访问时间,格式为自 1970 年 1 月 1 日午夜 GMT 以来经过的毫秒数。

6

*public int getMaxInactiveInterval()*此方法返回最大的时间间隔(秒),即 servlet 容器在客户端访问之间保持会话打开的时间。

7

*public void invalidate()*此方法使此会话无效并解绑绑定到它的任何对象。

8

*public boolean isNew(*该方法在客户端还不知道会话或者客户端选择不加入会话的情况下返回 true。

9

*public void removeAttribute(String name) *该方法从此会话中移除使用指定名称绑定的对象。

10

*public void setAttribute(String name, Object value) *该方法用指定名称绑定一个对象到当前会话。

11

*public void setMaxInactiveInterval(int interval) *该方法指定会话在 Servlet 容器将此会话无效化之前,两次客户端请求之间的时间(秒)。

Session Tracking Example

此示例描述了如何使用 HttpSession 对象找出会话的创建时间和上次访问时间。如果尚未存在会话,我们将为请求关联一个新会话。

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Extend HttpServlet class
public class SessionTrack extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

      // Create a session object if it is already not  created.
      HttpSession session = request.getSession(true);

      // Get session creation time.
      Date createTime = new Date(session.getCreationTime());

      // Get last access time of this web page.
      Date lastAccessTime = new Date(session.getLastAccessedTime());

      String title = "Welcome Back to my website";
      Integer visitCount = new Integer(0);
      String visitCountKey = new String("visitCount");
      String userIDKey = new String("userID");
      String userID = new String("ABCD");

      // Check if this is new comer on your web page.
      if (session.isNew()) {
         title = "Welcome to my website";
         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");
      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 Infomation</h2>\n" +
               "<table border = \"1\" align = \"center\">\n" +

                  "<tr bgcolor = \"#949494\">\n" +
                     "  <th>Session info</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>" + 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>"
      );
   }
}

编译上面的 servlet SessionTrack 并创建 web.xml 文件中适当的条目。现在运行 [role="bare"] [role="bare"]http://localhost:8080/SessionTrack ,当您第一次运行时,将显示以下结果 −

Welcome to my website
Session Infomation


Session info
value


id
0AE3EC93FF44E3C525B4351B77ABB2D5


Creation Time
Tue Jun 08 17:26:40 GMT+04:00 2010


Time of Last Access
Tue Jun 08 17:26:40 GMT+04:00 2010


User ID
ABCD


Number of visits
0

现在尝试第二次运行相同的 servlet,它将显示以下结果。

Welcome Back to my website
Session Infomation


info type
value


id
0AE3EC93FF44E3C525B4351B77ABB2D5


Creation Time
Tue Jun 08 17:26:40 GMT+04:00 2010


Time of Last Access
Tue Jun 08 17:26:40 GMT+04:00 2010


User ID
ABCD


Number of visits
1

Deleting Session Data

完成用户的会话数据时,您有几种选择 −

  1. Remove a particular attribute − 可以调用 public void removeAttribute(String name) 方法以删除与特定键关联的值。

  2. Delete the whole session − 可以调用 public void invalidate() 方法以放弃整个会话。

  3. Setting Session timeout − 可以调用 public void setMaxInactiveInterval(int interval) 方法来单独设置会话超时。

  4. Log the user out − 支持 servlet 2.4 的服务器,您可以调用 logout 让客户端从 Web 服务器注销并使属于所有用户的会话无效。

  5. web.xml Configuration − 如果使用 Tomcat,除了上述方法之外,还可以按照如下方式在 web.xml 文件中配置会话超时。

<session-config>
   <session-timeout>15</session-timeout>
</session-config>

超时时间表示为分钟数,并覆盖 Tomcat 中的默认超时时间(30 分钟)。

servlet 中的 getMaxInactiveInterval( ) 方法以秒为单位返回该会话的超时时间。因此,如果在 web.xml 中为您的会话配置 15 分钟,则 getMaxInactiveInterval( ) 返回 900。