How to use session technology (cookie&session) in personal web projects?

Compilation software: IntelliJ IDEA 2019.2.4 x64
Operating system: win10 x64-bit Home Edition
Server software: apache-tomcat-8.5.27



1. What is a session?

Open Baidu Encyclopedia's entry on " session ", which is described as follows: " In computer terms, a session refers to the process of communicating between an end user and an interactive system, such as entering the account password to enter the operating system to exiting the operating system. A conversational process. ", of course, it is true.

When the client (end user) communicates with the server, starting from a request from the client to the server and ending with a response from the server to the client, we call it an interaction . For example, when we log in to the Bank of China app to check the balance of the bank card, when we click the query button on the software to display the balance number on the app, there is an interaction.

A session is composed of one or even n interactions. For example, the process from logging in to the Bank of China app to exiting the app is a conversational process.


2. Why use conversational technology?

Purpose:

To keep users logged in

What's the meaning?

After the user logs in, the user's login status will be saved in the server. When the user subsequently accesses other dynamic resources in the web project and responds through (Servlet or Thymeleaf), it can determine whether the user has already logged in.
In this way, even if the user slips and forks off the homepage link of the server, and clicks to log in again, there is no need to repeatedly enter the user name and password to log in.

benefit:

  • Can improve user experience and reduce repetitive operations
  • It helps to provide more personalized services, allowing users to experience a more efficient and convenient experience.

3. How to use conversational technology?

3.1 Cookie (client session technology)

Introduction:

Cookie is a client-side session technology. It is a small piece of data stored by the server in the browser (client) , and the browser will carry this small piece of data to the server every time it visits the server.

effect:

  1. Store data in the browser
  2. Carry the data stored in the browser to the server

3.1.1 How to save data in cookie?

step:

  1. Create Cookie object and set data

  2. Add cookie to response message

Case: Demonstration of creating a cookie object and adding it to the response message

The code demonstration is as follows:

//1.创建Cookie对象并设置数据(ke与value的结构)
Cookie cookie01=new Cookie("adminKey","adminValue");
Cookie cookie02=new Cookie("rootKey","rootValue");
//2.将cookie添加到响应报文
response.addCookie(cookie01);
response.addCookie(cookie02);

insert image description here

Characteristics of cookie data:

  • 一旦cookie被保存到客户端,在以后的每次请求中都会带着所有的cookie

    Notice:

    Suppose you use Google browser to save the newly set cookie at this time, and then open a browser to connect to the server and send a request, you cannot get the cookie stored in Google browser

  • 此时添加cookie被称为瞬时cookie,一旦浏览器关闭,cookie就会消失(浏览器关闭,会话就结束)

    Thinking: Why does this cookie disappear as soon as the browser is closed?

    It is called a transient cookie because it is stored in running memory . When each program on our computer is started, the CPU will allocate a process for the program, and the process will get an independent memory, and the cookie will be stored in this independent running memory. Therefore, as soon as the browser process ends, the cookie will naturally disappear.

3.1.2 How to get the data out of the cookie?

Case: Demonstration to take out the cookie value just set

The code demonstration is as follows:

//从请求报文中获得cookie,返回cookie列表
Cookie[] cookies = request.getCookies();
//判断cookie列表中有无空值,避免空指针异常
if (cookies!=null){
    
    
    //遍历列表中的每一个cookie
    for (Cookie cookie : cookies) {
    
    
        //获得cookie的key值
        System.out.println(cookie.getName());
        //获得cookie的value值
        System.out.println(cookie.getValue());
    }
}

3.1.3 Valid time of cookie data

If we do not set the validity period of the cookie, the validity period of the cookie is within the scope of one session by default , and we can use the cookie setMaxAge()method to make the cookie persistent and save it to the browser

  • Session-level cookies (no expiration time set)
    • The server does not explicitly specify the lifetime of the cookie
    • On the browser side, cookie data exists in memory
    • As long as the browser is still open, the cookie data is always there
    • When the browser is closed, the cookie data in the memory will be released
  • Persistent Cookie (with valid time set)
    • The server side explicitly sets the lifetime of the cookie
    • On the browser side, the cookie data will be saved to the hard disk
    • The time that cookies exist on the hard disk is controlled according to the time limited by the server, and is not affected by the closing of the browser
    • The persistent cookie will be released when the preset time is reached

cookie.setMaxAge(int expiry)The parameter unit is seconds , indicating the persistence time of the cookie. If the parameter is set to 0, it means that the cookie saved in the browser will be deleted

Where to set: Set its valid time before adding it to the response message

The code example is as follows:

//设置cookie的有效时间,在该时间段内,该cookie会存放在磁盘,时间一过,它会消失
cookie01.setMaxAge(60);//单位是秒

3.1.4 Setting the conditions for carrying cookies

Interpretation:

What kind of request path do you want to carry the cookie

Example:

If we want to carry a certain cookie under access to " http://localhost:8080/day11_ajax_war_exploded/root " and have set the conditions, type the request path in the browser URL bar, after the browser sends the request, the request message will
Include the cookie value and pass it to the server, and the server can get the cookie.

The location of the setting: set a request path before adding the response message

The code example is as follows:

//设置cookie01只有在访问当前项目下的user下的请求时才会携带
cookie01.setPath(request.getContextPath()+"/user");//设置一个uri

3.1.5 Case (login page: remember user and password)

Case Requirement: Realize remembering username and password on the login page

The code example is as follows:

① Build Thymeleaf environment

a. Import Thymeleaf related jar packages

insert image description here

b. Paste viewBaseServlet
c. Configure Thymeleaf prefix and suffix in web.xml

<!--thymeleaf的前缀和后缀-->
<context-param>
    <param-name>view-prefix</param-name>
    <param-value>/WEB-INF/pages/</param-value>
</context-param>
<context-param>
    <param-name>view-suffix</param-name>
    <param-value>.html</param-value>
</context-param>

② Introduce hyperlinks to access the login interface in index.html, prepare the login interface (login.html) and login success interface (login_success.html), and introduce Thymeleaf rendering expressions

//准备登录界面(login.html)并引入Thymeleaf渲染表达式
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <base th:href="@{/}">
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="cookie?flag=login" method="post">
        用户名:<input type="text" name="username" th:value="${username}"><br>
        密码:<input type="password" name="password" th:value="${password}"><br>
        <input type="checkbox" name="confirm"/>记住用户名和密码<br>
        <input type="submit" value="登录">
    </form>
</body>
</html>
//准备登录成功界面(login_success.html)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>登录成功</h1>
</body>
</html>

③ Write related codes in cookieServlet to realize functions

Realize the function idea:

After the user enters the user name and password on the login interface, clicks to log in, the browser sends a request, CookieServlet receives the request, calls the login() method, and determines that the user name and password are correct and the user has checked "Remember user name and password" , it will obtain the request parameters username and password from the request message and assign them to two cookie objects, and store these two cookie objects in the response message, the purpose is to let the browser store these two cookies when responding to the browser . Then when you visit the "login" interface on the home page, request to CookieServlet, CookieServlet calls the tologin()f method, takes out the cookie in the request message, stores it in the request domain, and finally uses thymeleaf to render the login interface. A cookie is taken from the request field and replaced into the thymeleaf rendering expression [th:value="${password}"] of the username and password in the form in login.html, and a view object is generated to respond to the browser

//转发至login.html
protected void tologin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
    String username="";
    String password="";
    Cookie[] cookies = request.getCookies();
    if (cookies!=null){
    
    
        for (Cookie cookie : cookies) {
    
    
            if ("username".equals(cookie.getName())){
    
    
                username=cookie.getValue();
            }else if ("password".equals(cookie.getName())){
    
    
                password=cookie.getValue();
            }
        }
    }
    request.setAttribute("username",username);
    request.setAttribute("password",password);
    this.processTemplate("login",request,response);
}

//登录功能实现
protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String confirm = request.getParameter("confirm");


    if ("admin".equals(username) && "123456".equals(password)){
    
    
        if (confirm!=null){
    
    
            //设置cookie
            Cookie usernameCookie=new Cookie("username",username);
            Cookie passworCookie=new Cookie("password",password);

            //设置cookie的有效时间
            /*usernameCookie.setMaxAge(60*3);
            passworCookie.setMaxAge(60*3);*/

            //在响应报文中添加cookie
            response.addCookie(usernameCookie);
            response.addCookie(passworCookie);
        }
        //登录成功跳转至login_success.html
        System.out.println(username+"登录成功");
        this.processTemplate("login_success",request,response);
    }else {
    
    
        //登录失败停留在当前页面(login.html)
        System.out.println("用户名或密码错误");
        this.processTemplate("login",request,response);
    }


}

insert image description here

insert image description here

insert image description here

3.2 Session (server-side session technology)

Introduction:

Session is a server-side technology, and data is stored on the server side. The server opens up a memory space for each browser, namely the session object. Since the session object is unique to each browser, user records can be stored in the session object

Notice:

  • The server will create a Session object for each client. If the client needs a session object every time it visits, it will return the previously created
  • The server-side session starts from the first time the Httpsession object is obtained, and ends when the Httpsession object is destroyed

3.2.1 What is a session domain?

In web applications, session scope (Session Scope) refers to the scope visible within a session cycle . It is typically used to store data that needs to be shared and accessed across multiple requests throughout a session.

Its relationship with request domain and application domain:

In Java Web development, 会话域(Session Scope), 请求域(Request Scope) and 应用域(Application Scope) all refer to data storage methods visible in different scopes. They have the following relationship:

  1. 会话域: A session corresponds to an HttpSession object, and the life cycle is consistent with the session. Data stored in the session domain is accessible throughout the session, including across multiple requests. You can use the methods provided by the HttpSession object to add, get, or delete data from the session.
  2. 请求域: A request corresponds to a HttpServletRequest object, and the data stored in the request field is only valid in the current request. Through methods such as setAttribute() and getAttribute() provided by the HttpServletRequest object, data can be added and obtained in the request field.
  3. 应用域: An application corresponds to a ServletContext object, and the data stored in the application domain can be accessed throughout the running of the application . You can use the methods provided by the ServletContext object to add, get, or delete data from the application domain.

To sum up: the difference between them mainly lies in the scope and life cycle of stored data . The session domain is suitable for storing data that needs to be shared and accessed across multiple requests, and it is saved throughout the session cycle; the request domain is suitable for storing data that is only valid in the current request; the application domain is suitable for storing globally common data, and it is stored during the entire application run can be accessed.

The relationship between them is a containment relationship , that is, the application domain is the top-level container of all scopes, the session domain is the top-level container of the request domain, and the request domain contains its own scope and the bound sub-requests forwarded or included Request domain data. When storing and accessing data, it is necessary to flexibly select the appropriate scope according to the actual usage scenario, and use the corresponding API to operate.

3.2.2 What methods does session have?

①Get Httpsession object

Note: Get the session (if the session is actually created when the first call is made, the session can be found and used by sessionId after the first call)

The code example is as follows:

request.getsession();

②Set shared data

The code example is as follows:

//在会话域内设置共享数据(key为sessionMsg,value为sessionvalue),根据key找到对应的value
session.setAttribute("sessionMsg","sessionvalue");

③ Obtain shared data

The code example is as follows:

//在会话域内根据key为sessionMsg找对应的共享数据
object sessionMsg=session.getAttribute("sessionMsg");

④Remove shared data

The code example is as follows:

//从请求域内删除key为sessionMsg的共享数据
session.removeAttribute("sessionMsg");

Case: Create hyperlinks of four methods in index.html, including "Get Httpsession Object", "Set Shared Data", "Get Shared Data", and "Remove Shared Data" to access SessionServlet, and call the methods created in it in turn, Open two browsers and click the above four hyperlinks to observe the demonstration effect

The code demonstration is as follows:

①Create SessionServlet and configure its access path/session in web.xml

//创建SessionServlet并在web.xml中配置其访问路径 /session
<servlet>
    <servlet-name>SessionServlet</servlet-name>
    <servlet-class>Servlet.module.SessionServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>SessionServlet</servlet-name>
    <url-pattern>/session</url-pattern>
</servlet-mapping>

②Create hyperlinks of four methods in index.html to access SessionServlet

//在index.html中创建四个方法的超链接以访问SessionServlet
<a href="session?flag=getsession">获得session对象</a><br>
<a href="session?flag=setValuesession">在session会话域内设置共享数据</a><br>
<a href="session?flag=getValuesession">在session会话域内获得之前设置的共享数据</a><br>
<a href="session?flag=removeValuesession">在session会话域内删除之前设置的共享数据</a><br>

③SessionServlet implements its four methods

//SessionServlet实现其四个方法
import Servlet.base.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionServlet extends BaseServlet {
    
    
    protected void getsession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //获得session对象,从这开启会话
        HttpSession session = request.getSession();
        System.out.println("session = "+session);

    }

    protected void setValuesession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //获得并打印session对象,
        HttpSession session = request.getSession();
        System.out.println("session = "+session);
        //在会话域设置共享数据(key与value)【sessionKey=sessionValue】
        session.setAttribute("sessionKey","sessionValue");
    }

    protected void getValuesession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //获得并打印session对象,
        HttpSession session = request.getSession();
        System.out.println("session = "+session);
        //获取在会话域设置的共享数据(key与value)
        Object sessionKey = session.getAttribute("sessionKey");//【sessionValue】
        System.out.println("sessionKey = "+sessionKey);
    }

    protected void removeValuesession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //获得并打印session对象,
        HttpSession session = request.getSession();
        System.out.println("session = "+session);
        //删除在会话域设置的共享数据(key与value)【sessionValue】
        session.removeAttribute("sessionKey");
        Object sessionKey = session.getAttribute("sessionKey");
        System.out.println("sessionKey = "+sessionKey);
    }
}

insert image description here

insert image description here

3.2.3 How does the server distinguish the corresponding relationship between the client and the session object?

why?

It is distinguished through cookies! Session depends on cookie.

Implementation principle:

①When the client accesses the server for the first time, call getsession(), create a new session object, and set a cookie to the browser (jsessionid)

insert image description here

②When the client visits the server for the second time, it calls getsession() to obtain the jsessionid cookie in the request, and finds the session object through the value of the cookie

insert image description here

3.2.4 When does a session end?

①The client is closed (the jsessionid cookie disappears)

② Forced failure

The code example is as follows:

session.invalidate();//强制失效

③Automatic invalidation (maximum idle time reached)

The default is half an hour (no operation, no request has been sent to the server), and the maximum idle time is calculated from the last request before no operation

The code example is as follows:

session.setMaxInactiveInterval(30);//单位是秒

3.2.5 Session application scenarios

①It is usually used to store specific user-related information in Web applications , such as

Login interface: keep the user logged in, log out

Implementation idea:

In the method of logging in the servlet, place the bean object returned according to the business layer query in the session domain, and use the bean object in the session domain to maintain the login status

② It can also store various user-related data, such as user ID, user name, role, shopping cart and so on. These data can be set, retrieved, and deleted by server-side code. Using Session, you can achieve the following functions:

1. 用户认证和授权: Use Session to store information such as user name and password entered by the user when logging in, corresponding permissions, etc., to ensure that only authenticated users can access protected resources in the application.

2. 数据持久化: Session can use Cookie or URL Rewriting technology to save data on the client, or in server memory or file, so as to achieve data persistence.

3. 业务逻辑处理: According to the information saved in the current Session, logical operations can be performed in the background, such as shopping cart calculation.

3.2.6 What is the working mechanism of the getsession() method?

premise:

The browser accesses the server normally

Working Mechanism:

1. Call getsession() to create a session object, and determine whether the cookie JSESSIONID exists in the request

判断存在: Go according to the cookie value corresponding to JSESSIONID, and then find the corresponding session object in the server

a. 如果找到了session对象: Just return the session object directly

b. 找不到session对象: Create a new session object and set the JSESSIONID cookie

判断不存在: Create a new session object and set the cookie JSESSIONID

insert image description here


Guess you like

Origin blog.csdn.net/siaok/article/details/130296507