当前位置:网站首页>[web] cookies and sessions

[web] cookies and sessions

2022-06-13 03:49:00 Bryant tapping the code

Blog home page : Bryant typing the code
Welcome to thumb up
Collection Leaving a message. Welcome to discuss !
This paper is written by 【 Bryant typing the code 】 original , First appeared in CSDN

Because the blogger is learning Xiaobai one , There are bound to be mistakes , If you have any questions, please leave a message in the comment area to point out , Be deeply grateful !
Boutique column ( Update from time to time )
JavaSE】 【Java data structure 】【LeetCode
 Insert picture description here

review Cookie

HTTP The agreement itself belongs to “ No state ” agreement .

“ No state ” Means :
By default HTTP This communication between the client and server of the protocol , There is no direct connection with the next communication .

But in actual development , We often need to know the relationship between requests .
For example, after successfully logging in to the website , During the second visit, the server can know whether the request has been logged in .

 Insert picture description here
adopt set-cookie Return to the browser and store in Cookie Things in fields are like A token given by the server to the client Used for identification and identification

At this time in The server We need it here Record token information , And the user information corresponding to the token , This is Session The work done by the mechanism .

Understanding conversational mechanisms (Session)

The server receives many requests at the same time . The server needs to be cleared to distinguish which user each request belongs to , You need to record the corresponding relationship between each user token and user information on the server side .

It's like going to the hospital , A doctor's card is a card “ token ”. For this token to work , The hospital needs to record the relationship between each visit card and patient information through the system .

The essence of conversation is a “ Hashtable ”, Stored some key value pair structures . key Namely Token ID(token/sessionId), value Namely User information ( User information can be flexibly designed according to requirements ).

sessionId Is a generated by the server “ Uniqueness string ”, from session From the perspective of mechanism , This unique string is called “sessionId”. But look at it in the whole login process , You can also call this unique string “token”. sessionId and token It can be understood as different names of the same thing ( Different perspectives )

 Insert picture description here

Servlet Of Session The default is stored in memory .
If you restart the server Session The data is lost .

Cookie and Session The difference between

  • Cookie yes client The mechanism of . Session yes Server side The mechanism of .
  • Cookie and Session Often used together . But you don't have to cooperate .
  • It can be used completely Cookie To save some data on the client . These data are not necessarily user identity information , It doesn't have to be
    token / sessionId
  • Session Medium token / sessionId You don't have to pass Cookie / Set-Cookie Pass on .

The core approach

HttpServletRequest Related methods in class

Method describe
HttpSession getSession() Get the session in the server . If the parameter is true, Create a new session when there is no session ; If the parameter is false, Returns... When there is no session null
Cookie[ ] getCookies() Returns an array , Contains all of the Cookie object . Will automatically Cookie The format in is parsed into key value pairs .

HttpServletResponse Related methods in class

Method describe
void addCookie(Cookie cookie) The specified cookie Add to response .

HttpSession Related methods in class

One HttpSession Inside the object Contains multiple key value pairs . We You can go HttpSession Save any information we need .

Method describe
Object getAttribute(Stringname) The method returns the value in the session The object with the specified name in the session , If there is no object with the specified name , Then return to null.
void setAttribute(Stringname, Object value) This method binds an object to the object with the specified name session conversation boolean isNew() Determine whether the current session is a newly created session

Cookie Related methods in class

Every Cookie An object is a key value pair .

Method describe
String getName() This method returns cookie The name of . The name cannot be changed after creation .( This value is SetCooke Field set to the browser )
String getValue() This method obtains and cookie The value of the Association
void setValue(StringnewValue) This method is set up with cookie The value of the Association .
  • HTTP Of Cooke What is stored in the field is actually multiple sets of key value pairs . Each key value pair is in Servlet All correspond to one Cookie object .
  • adopt HttpServletRequest.getCookies() Get a series of... In the request Cookie Key value pair .
  • adopt HttpServletResponse.addCookie() You can add a new... To the response Cookie Key value pair .

Code example : Realize user login

Implement simple user login logic
This code is mainly through HttpSession class complete . We don't need to operate it manually Cookie object .

1. Achieve a landing page

<!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> land </title>
</head>
<body>
    <form action="login" method="POST">
           <input type="text" name="username">
           <input type="password" name="password">
           <input type="submit" value=" Submit ">
       </form>
</body>
</html>

2. Achieve one Servlet Used to process login requests

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;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
    
        resp.setContentType("text/html; charset=utf-8");
        // 1.  Get the user name and password submitted by the user 
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 2.  Determine whether the user name and password are correct 
        if (!username.equals("kobe") || !password.equals("824")) {
    
            //  Login failed 
            resp.getWriter().write(" Login failed ");
            return;
        }
        //  Landing successful 
        System.out.println(" Landing successful ");
        //  Set up  Session
        HttpSession session = req.getSession(true);
        session.setAttribute("username", "Kobe Bryant");
        session.setAttribute("loginCount", "");
        resp.sendRedirect("index");
    }
}

 Insert picture description here
 Insert picture description here

3. One more IndexServlet To represent the home page after redirection

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;
import java.io.IOException;

@WebServlet("/index")
public class IndexServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
    
        resp.setContentType("text/html; charset=utf-8");
        // 1.  Determine whether the current user has logged in 
        HttpSession session = req.getSession(false);
        if (session == null) {
    
            //  The user didn't log in ,  Redirect to  login.html
            resp.sendRedirect("login.html");
            return;
        }
        // 2.  If you have logged in ,  From  Session  Fetch the number of accesses data from 
        String userName = (String)session.getAttribute("username");
        String countString = (String)session.getAttribute("loginCount");
        int loginCount = Integer.parseInt(countString);
        loginCount += 1;
        session.setAttribute("loginCount", loginCount + "");
        // 3.  Show on page .
        StringBuilder html = new StringBuilder();
        html.append(String.format("<div> user name : %s</div>", userName));
        html.append(String.format("<div>loginCount: %d</div>", loginCount));
        resp.getWriter().write(html.toString());
    }
}

 Insert picture description here

Realization effect

 Insert picture description here

 Insert picture description here

原网站

版权声明
本文为[Bryant tapping the code]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206130334279740.html