cookie&session&simulated login

cookie

What are cookies?
A cookie is a mechanism for persistent storage of data provided by browsers

Where do cookies come from?
The cookie is returned from the server to the browser.
In the server code, the programmer decides what information to save to the client side, and the key-value pair can be written back through the Set-cookie field of the HTTP response.

Where do cookies go?
The cookie will be brought to the header of the request when the subsequent browser accesses the server and sent to the server.
why? Because the server not only provides services to one client, but also handles multiple clients at the same time, the server can use the value in the cookie to identify who the current client is, what the current client service provides, etc. (client The end lets the server know who he is through the cookie)

Where are cookies stored?
Cookies are stored on the hard disk of the host machine where the browser (client) is located. The browser will store them separately according to the domain name.

example

The use of cookies is very wide, the most typical application is: to identify user identity information

For example: the website has a login function.
To log in to the website, the browser first sends a request to the server to obtain the homepage of the website,
and then the server returns the homepage of the website. At this time, the server does not know the identity information of the user.
Then the browser sends a login request. For the login request sent by the client, the server will query the database to verify whether the user information is correct. If it is correct, the login is successful. [At this time, the website will also save the current user's identity information in memory At the same time, assign an identity serial number (unique) to this user to represent the identity. The identity serial number here is called sessionId. The server uses the structure of the hash table to store the identity serial number as the key and the identity information as the value. The server refers to these generated key-value pairs as a session (session).
The information is correct, the server returns the login success, and returns the identity serial number, then the browser saves the identity serial number in the browser cookie.
In subsequent requests from the browser, when the server receives the identity serial number in the cookie, it will query the hash table to determine who the user is. If it is found, it will continue to perform the operation entered by the user to avoid repeatedly entering the account password. If not found, the user is required to log in again.

The server calls these generated key-value pairs session (session), and the generated unique identity serial number as sessionId

The association and difference between cookie and session:

Association: In the login function of the website, it needs to be used together
. Difference:

  1. Cookie is the storage mechanism of the client, and session is the storage mechanism of the server
  2. Various key-value pairs (others can also be stored) can be stored in the cookie, and the session is specially used to store user identity information.
  3. Cookies can be used alone without session (implementing non-login scenarios)
  4. Sessions can also be used without cookies (the mobile app logs in to the server, and the server also needs sessions, and there is no concept of cookies at this time). Cookies are strongly related to browsers.
  5. Cookie is a part of HTTP protocol, session can have nothing to do with HTTP (TCP, websocket can also use session)
  6. A domain name can have multiple cookies, but only one sessionId (cookie can not only be used to store identity information)

mock login code

There are two pages involved here

  1. Login page login.html
  2. The main page index.html
    clicks the button on the login page to trigger a login request. Loginservlet verifies whether the user name and password are correct at the back end. If the login is successful, it jumps to the new page index.html, where the user name is displayed and dynamically passed through the servlet. Build Indexservlet

Two servlets are involved.
3. The Loginservlet that handles the login determines the username and password.
4. Construct the Indexservlet of the main page

front-end code

login

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录</title>
</head>
<body>
    <form action="login" method="post">
        <input type="text" name="username">
        <br>
        <input type="password" name="password">
        <br>
        <input type="submit" value="提交">
    </form>
    
</body>
</html>

packet capture check
insert image description here

POST http://127.0.0.1:8080/hello_servlet2/login HTTP/1.1
Host: 127.0.0.1:8080
Connection: keep-alive
Content-Length: 25
Cache-Control: max-age=0
sec-ch-ua: “Google Chrome”;v=“111”, “Not(A:Brand”;v=“8”, “Chromium”;v=“111”
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: “Windows”
Upgrade-Insecure-Requests: 1
Origin: http://127.0.0.1:8080
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,/;q=0.8,application/signed-exchange;v=b3;q=0.7
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Referer: http://127.0.0.1:8080/hello_servlet2/login.html
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
/
username=123&password=qwe

backend code

login

Each session is a key-value pair corresponding to a client. The server can correspond to multiple clients here, and there are multiple sets of sessions.
In each session object HttpSession, some data defined by the programmer can also be stored, which is also organized in the form of key-value pairs

key value
sessionId 123456 HttpSession key: “username” value :“zhangsan” key :“age” value :10
sessionId asdfghjk HttpSession key :“username” value :“zhangsan” key: “age” value: 10
sessionId 3456789 HttpSession key :“username” value: “wangyu”
  1. create session
HttpSession session = req.getSession(true);

The so-called session is a key-value pair, the key is the sessionId, and the value is the HTTPSession object
. Each session is a key-value pair, which corresponds to a client.
Each session object can store some programmer-defined data.
Each client has such a key-value pair (session) when logging in, and the server needs to manage multiple such sessions. The server
can create a hash table to organize these sessions.

getSession(true): Determine whether the current request already has a corresponding session
(check the hash table with the sessionId in the cookie in the request, if you don’t find a new session, insert it into the hash table; if you find it, return it directly Result)
getSession(false): if not found, no new session will be created, return null; if found, directly return
true and false: whether a new session can be created.

getSession(true) is not found, create a new session process:

  1. Construct an httpSession object

  2. Construct a unique sessionId

  3. Insert this key-value pair into the hash table

  4. Set the sessionId to the Set-Cookie field of the response message
    Note: The httpSession object itself is also a key-value pair, use getAttribute setAttribute to access the key-value pair here
    The key-value pair is completely programmer-defined data

  5. Save the current user name in the session, where the HttpSession object itself is also a key-value pair structure.

session.setAttribute("username", username);
session.setAttribute("password", passwd);
  1. redirect to home page
resp.sendRedirect("index");
@WebServlet("/login")
public class loginServlet extends HttpServlet {
    
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        String username = req.getParameter("username");
        String passwd = req.getParameter("password");

        //验证用户名密码是否正确,正常情况下,用户名密码用数据库保存,此处直接写死,代码进行判定
        //此处约定用户名 root  admin  密码123
        if (!username.equals("root") && !username.equals("admin")) {
    
    
            // 登录失败
            // 重定向到登录页面
            System.out.println("登录失败,用户名错误");
            resp.sendRedirect("login.html");
            return;
        }
        if (!passwd.equals("123")) {
    
    
            // 登录失败
            System.out.println("登录失败,密码错误");
            resp.sendRedirect("login.html");
            return;
        }
        // 登录成功
        System.out.println("登录成功");
        //1. 创建会话
        HttpSession session = req.getSession(true);

        //2. 把当前的用户名保存到会话中,此处的 HttpSession 对象自己也是一个键值对结构。
        session.setAttribute("username", username);
        session.setAttribute("password", passwd);
        //3. 重定向到主页
        resp.sendRedirect("index");

    }
}

index

Through redirection, the browser initiates a GET request

In login Servlet redirect is index

resp.sendRedirect("index");

In indexServlet, it needs to be consistent with the above redirected page label

@WebServlet("/index")
@WebServlet("/index")
public class indexServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        // 先判定用户的登陆状态
        // 如果用户没登录,要求先登录
        // 如果已经登录,根据会话中的用户名,显示到页面上
        HttpSession session = req.getSession(false);  //获取 如果没有也不会创建新会话
        if (session == null) {
    
    
            System.out.println("用户未登录");
            resp.sendRedirect("login.html");
            return;
        }

        //用户登录了
        //此处可以这样取,前提是前面的登录操作中存了。
        //HttpSession value的值是Object,需要手动强转成String(设定Object就是可以转换成各种理想)
        String username = (String) session.getAttribute("username");
//        String passwd = (String) session.getAttribute("password");
        resp.setContentType("text/html; charset=utf8");
        resp.getWriter().write("welcome~ " + username + " come back");
    }
}

Guess you like

Origin blog.csdn.net/weixin_44431128/article/details/129637595