What is a session? How does a servlet maintain a session?

session:

Maintaining the association between a user and different requests made by the same user across multiple HTTP connections is called maintaining a session.

A tcp connection is established, but many HTTP requests can be sent, and the session records user information, so it can be judged that these requests are from the same user. For example, when Taobao is added to browse many kinds of products, it is a lot of HTTP requests.

There are three ways to maintain the session session between the Web client and the Web server:

Cookies
A web server can assign a unique session session ID as a cookie for 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 it is recommended not to use this method to maintain session sessions.
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="session_id" value="12345">
This entry means that the specified name and value are automatically included in the GET or POST data when the form is submitted. The session_id value can be used to keep track of a different web browser each time the web browser sends a request back.
This can be an efficient way to keep track of session sessions, but clicking on regular hypertext links (<A HREF...>) will not cause the form to submit, so hidden form fields don't support regular session tracking either.
URL rewriting
You can append some additional data to the end of each URL to identify the session session, and the server will associate the session session identifier with stored data about the session session.
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 a session session, it works well when the browser does not support cookies, but it has the disadvantage that each URL is dynamically generated to assign a session session ID to the page, even if This is true even in very simple static HTML pages.

HttpSession Object
The servlet also provides the HttpSession interface, which provides a way to identify and store information about a user when requesting or accessing a website across multiple pages.
The servlet container uses this interface to create a session between the HTTP client and the HTTP server. A session lasts for a specified period of time, across multiple connections or page requests.

The HttpSession object is obtained by calling the public method getSession() of HttpServletRequest.

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

Session trace instance

本实例说明了如何使用 HttpSession 对象获取 session 会话创建时间和最后访问时间。如果不存在 session 会话,我们将通过请求创建一个新的 session 会话。

package com.runoob.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("Runoob");
    
        // 检查网页上是否有新的访问者
        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>Visit Statistics:</td>\n" +
                "  <td>" + visitCount + "</td></tr>\n" +
                "</table>\n" +
                "</body></html>");
    }
}
For specific reference, the rookie tutorial click to open the link

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324753856&siteId=291194637