📜  Servlet – 会话跟踪

📅  最后修改于: 2022-05-13 01:55:35.098000             🧑  作者: Mango

Servlet – 会话跟踪

Servlet 是在支持Java的 Web 服务器或应用程序服务器上运行的 Java 程序。它们用于处理从网络服务器获得的请求,处理请求,产生响应,然后将响应发送回网络服务器

HTTP 是一种“无状态”协议,这意味着每次客户端请求网页时,客户端都会与 Web 服务器建立新的连接,服务器不会保留对先前请求的跟踪。

  • 用户在一段时间内的转换称为会话。一般来说,它是指一定的时期。
  • 会话中对象的记录称为跟踪
  • 会话跟踪是随着时间的推移记住和记录客户转化的过程。会话管理是它的另一个名称。
  • 术语“有状态的 Web 应用程序”是指能够随时间记住和记录客户端转换的 Web 应用程序。

为什么需要会话跟踪?

  • 因为 HTTP 协议是无状态的,所以我们需要 Session Tracking 来使客户端-服务器关系有状态。
  • 会话跟踪对于跟踪在线购物、邮件应用程序和电子商务应用程序中的转化非常重要。
  • HTTP 协议是无状态的,这意味着每个请求都被视为一个新请求。如下图所示。

删除会话数据

一旦您完成了用户会话数据的处理,我们有多种选择。

  1. 删除特定属性 您可以通过调用 public void removeAttribute(String name)函数删除与特定键关联的值。
  2. 删除整个会话。要删除整个会话,请使用 public void invalidate()函数。
  3. 设置会话超时 您可以通过调用 public void setMaxInactiveInterval(int interval)函数单独设置会话的超时。
  4. 注销用户 在支持 servlet 2.4 的服务器上,您可以使用注销方法将客户端从 Web 服务器注销,并使所有用户的会话无效。
  5. web.xml 配置 如果您使用的是 Tomcat,除了上面列出的方法之外,您还可以在 web.xml 文件中设置会话超时。

  20

超时以分钟为单位指定并覆盖 Tomcat 的默认超时 30 分钟。

在 servlet 中,getMaxInactiveInterval()函数以秒为单位传递会话的超时期限。如果您的会话在 web.xml 中设置为 20 分钟,GetMaxInactiveInterval() 将返回 900。

会话跟踪采用四种不同的技术

  1. 饼干
  2. 隐藏表单域
  3. 网址重写
  4. HttpSession

A.饼干

Cookie 是 Web 服务器在响应标头中传递并由浏览器保存的小数据片段。 Web 服务器可以为每个 Web 客户端分配一个唯一的会话 ID。 Cookie 用于保持会话继续进行。客户端可以关闭 Cookie。

B.隐藏表单域

信息通过隐藏的表单字段插入网页,然后传输到服务器。这些字段对用户的视图是隐藏的。

插图

C. URL 重写

对于每个请求和返回,通过 URL 附加一些数据作为请求参数。 URL 重写是保持会话管理和浏览器操作同步的更好技术。

D. HttpSession

用户会话由 HttpSession 对象表示。使用 HttpSession 接口在 HTTP 客户端和 HTTP 服务器之间建立会话。用户会话是跨越多个 HTTP 请求的用户数据的集合。

插图:

HttpSession session = request.getSession( );
Session.setAttribute("username", "password");

必须提出请求。在向客户端发送任何文档内容之前,您必须首先调用 getSession()。以下是 HttpSession 对象提供的最重要的方法列表:

Method

Description

public Object getAttribute(String name)This method returns the object in this session bound with the supplied name, or null if no object is bound with the name.
public Enumeration getAttributeNames()This function returns an Enumeration of String objects with the names of all the items associated with this session.
public long getCreationTime()This method returns the milliseconds since midnight January 1, 1970 GMT, when this session was created.
public String getId()This function returns a string that contains the session’s unique identification.
public long getLastAccessedTime()This function returns the session’s most recent accessible time in milliseconds since midnight on January 1, 1970 GMT.
public int getMaxInactiveInterval()The maximum time interval (seconds) for which the servlet container will keep the session open between client requests is returned by this function.
public void invalidate()This function unbinds any objects connected to this session and invalidates it.
public boolean isNew()If the client is unaware of the session or decides not to join it, this function returns true.
public void removeAttribute(String name)The object bound with the supplied name is removed from this session using this method.
public void setAttribute(String name, Object value)This function uses the supplied name to tie an object to this session.
public void setMaxInactiveInterval(int interval)This function defines the interval between client requests before the servlet container invalidates this session in seconds.

实现:它描述了如何使用 HttpSession 对象获取会话的创建和上次访问时间。如果请求还没有与之关联的会话,我们将创建一个。

A.文件: Gfg 会话。Java

Java
// Java Program to Illustrate Creation and last-accessed
// Times for a Session
 
// Import required java libraries
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
// Extend HttpServlet class
public class GfgSession 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 geeksforgeeks";
        Integer visitCount = new Integer(0);
        String visitCountKey = new String("visitCount");
        String userIDKey = new String("userID");
        String userID = new String("GFG");
 
        // Check if this is new comer on your web page.
        if (session.isNew()) {
            title = "Welcome to GeeksForGeeks";
            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
            = "\n";
 
        out.println(
            docType + "\n"
            + "" + title + "\n"
            +
 
            "\n"
            + "

" + title + "

\n"             + "

Gfg Session Information

\n"             + "\n"             +               "\n"             + "  "             + "\n"             +               "\n"             + "  \n"             + "  "             + "\n"             +               "\n"             + "  \n"             + "  "             + "\n"             +               "\n"             + "  \n"             + "  "             + "\n"             +               "\n"             + "  \n"             + "  "             + "\n"             +               "\n"             + "  \n"             + "  "             + "\n"             + "
Session infovalue
id" + session.getId() + "
Creation Time" + createTime + " 
Time of Last Access" + lastAccessTime + "
User ID" + userID + "
Number of visits" + visitCount + "
\n"             + ""             + "");     } }


XML


   GfgSession
   GfgSession

 

   GfgSession
   /GfgSession



B.文件:web.xml

XML



   GfgSession
   GfgSession

 

   GfgSession
   /GfgSession


输出:

如果我们再次尝试运行相同的 servlet,我们将得到以下结果。