Web learning history record (10) - cookie/session

conversation

Common Conversational Techniques

Cookie
is a client-side technology, and the program writes each user's data to the user's respective browser in the form of a cookie. When the user uses the browser to access the web resource transaction in the server, he will bring his own data with him. In this way, the web resource processes the user's own data.

Session
is a server-side technology, and the server opens up a memory space for each browser, that is, session. Since the memory space is exclusive to each browser, when all users visit, the information can be saved in the session object. At the same time, each session object corresponds to a sessionid, and the server writes the sessionid into the cookie. When visiting again, the browser will bring the cookie to find the corresponding object

Cookie

It is a client-side session technology. It is a small piece of data stored in the browser by the server. Every time the browser visits the server in the future, it will carry this small piece of data to the server.

Function
Store data in the browser
Carry the data stored in the browser to the server

Related APIs

//创建一个cookie对象
new Cookie(String name,String value);
//将cookie写回浏览器
response.addCookie(cookie);
//获得浏览器带过来的cookie
request.getCookies();

//返回cookie中设置的key
cookie.getName();
//返回cookie中设置的value
cookie.getValue();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
    Cookie[] cookies = request.getCookies();
    if (cookies != null){
    
    
        for (Cookie cookie : cookies) {
    
    
            if ("akey".equals(cookie.getName())){
    
    
                System.out.println(cookie.getValue());
            }
        }
    }
    Cookie cookie = new Cookie("akey","aaa");
    response.addCookie(cookie);
}

Generally, cookies are encapsulated

public class CookieUtils {
    
    
    public static Cookie getTargetCookie(String key,Cookie[] cookies){
    
    
        if (cookies == null){
    
    
            return null;
        }
        for (Cookie cookie : cookies) {
    
    
            if (key.equals(cookie.getName())){
    
    
                return cookie;
            }
        }
        return null;
    }
}

cookie classification

Session-level cookies
By default, cookies disappear when the browser process ends

Persistent cookie
sets the expiration date for the cookie
cookie.setMaxAge(int expiry);
-1: Default, means the data is saved until the browser is closed, and saved in the browser file
0: means delete the cookie, if you want to delete the cookie, ensure that the path is consistent and
greater than 0 : Save the data valid time in seconds (save the cached data to disk)

cookie set effective path

setPath(String url)

Function
Guarantee that cookies from other websites/projects will not be carried to our own project
If the path is different, the key of the cookie can be called to
ensure that our own project can reasonably use the cookie of our own project

The default path
is required to carry the cookie: the cookie will only be carried when the url of the accessed resource contains the effective path of the cookie

The cookie path is generally set like this:
cookie.setPath(request.getContextPath());

Case - Record users' respective last visit times

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        Cookie[] cookies = request.getCookies();
     Cookie targetCookie = CookieUtils.getTargetCookie("lasttime",cookies);
     if (targetCookie == null){
    
    
         Cookie cookie = new Cookie("lasttime",System.currentTimeMillis() + "");
         cookie.setMaxAge(60*60);
         cookie.setPath(request.getContextPath());
         response.addCookie(cookie);
         response.getWriter().print("第一次访问");
     }
     else {
    
    
//         Cookie cookie = new Cookie("lasttime",System.currentTimeMillis()+"");
//         cookie.setPath(request.getContextPath());
//         cookie.setMaxAge(60*60);
//         response.addCookie(cookie);
         String time = targetCookie.getValue();
         Date date = new Date(Long.parseLong(time));
         response.getWriter().print("你上次访问的事件是" + date.toLocaleString());
     }
    }

Session

is a server-side technology. The server opens up a memory space for each browser, that is, the session object

The different
cookies of cookie and session are saved on the browser side, and the size and number are limited. The session is saved on the server side. In principle, there is no limit on the size, so it is safer

Cookie does not support Chinese, and can only store strings; session can store basic data types, collections, objects, etc.

Execution process
Obtain the sessionId passed in the cookie (cookie)
If there is no sessionId in the cookie, create a session object
If there is a sessionId in the cookie, find the specified session object

If there is a sessionId and the session object exists, use it directly
If there is a sessionId but the session object is destroyed, then perform the second step

session based on cookie

Scope
session, saving user's respective data in units of browsers

request.getSession();
Object getAttribute(String name): get value
void setAttribute(String name,Object value); store value
void removeAttribute(String name); remove

Three Domain Objects Comparison
ServletContext
HttpSession
HttpServletRequest

If the server is shut down normally,
passivate the session to the server disk, restart it, and activate the files on the disk into the memory

How to choose the three domain objects
Under normal circumstances, the smallest can be solved with the smallest
redirection, multiple requests, session scope, and
session
If it is forwarding, generally choose request

Case: one-time verification code verification

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<center>
    <h1>用户登录:</h1>
    <form action="login" method="post">
        姓名:<input type="text" name="username"/><br/>
        密码:<input type="password" name="password"/><br/>
        验证码:<input type="text" name="code"/><br/>
        <img src="code" onclick="changeImg(this)"/><br/>
        <input type="submit" value="登录">
    </form>
</center>
</body>
</html>
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 java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset = utf-8");
        String usercode = request.getParameter("code");
        String code = (String) request.getSession().getAttribute("code");
        if (!code.equals(usercode)){
    
    
            response.getWriter().print("验证码有误");
            return;
        }

    }
}
import cn.dsna.util.images.ValidateCode;

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

@WebServlet("/code")
public class CodeServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        ValidateCode validateCode = new ValidateCode(200,50,4,100);

        String code = validateCode.getCode();
        System.out.println(code);
        request.getSession().setAttribute("code",code);

        validateCode.write(response.getOutputStream());

    }
}

Guess you like

Origin blog.csdn.net/qq_49658603/article/details/108474990