Cookies and Session (session technology)


Cookies and Session (session technology)

1. Cookies

1. Cookie overview

1.1. Introduction to Cookies

  1. Save data from the session to the user's browser.
  2. The server sends a letter to the client, and the client can just bring the letter with it the next time it visits the server.
  3. Client technology (response, request)
  4. The user opens a browser, clicks on many hyperlinks, accesses multiple web resources, and closes the browser. This process can be called a session (Cookie).
  5. A cookie can only save one piece of information.
  6. A web site can send multiple cookies to the browser, storing up to 20 cookies.
  7. Cookie size is limited to 4kb.
  8. Browser limit of 300 cookies.
  9. A session can contain multiple requests and responses.

1.2. Cookie usage scenarios

  1. It is often used to determine whether it is the first time to log in. If you do not need to log in next time, you will be logged in directly the second time!
1.3. The underlying principle of Cookie

Insert image description here

2. Basic use of cookies

  1. Cookie(name,value): Cookie construction method, stored in the form of key-value pairs
  2. addCookie(cookie): Added cookie
  3. getCookies(): Gets the array of Cookie objects when the request is sent
  4. getName(): Get the cookie name (key)
  5. getValue(): Get the value of Cookie
  6. setMaxAge(int expiry): Set the validity period of the cookie, in seconds, the default is -1 to survive permanently (but will be deleted when the browser is closed), 0 is deleted
  • RegistServlet.java
@WebServlet(name = "RegistServlet", value = "/registServlet")
public class RegistServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取前端传来的参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 判断输入的账号和密码是否正确
        if (username.equals("root")  && password.equals("111")){
    
    
            // 创建Cookie对象,键值对形式存放
            Cookie cookie1 = new Cookie("username", username);
            Cookie cookie2 = new Cookie("password", password);
            // 设置cookie的存活时间
            cookie2.setMaxAge(10); // 以秒为单位,默认为-1永久存活(但是会在浏览器关闭时被删除),0为删除
            // 在响应时添加cookie
            response.addCookie(cookie1);
            response.addCookie(cookie2);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doGet(request, response);
    }
}
  • regist.jsp
<%@ page import="java.util.Arrays" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册</title>
</head>
<body>
<%--编写 jsp 小脚本--%>
<%
    // getCookies():获取请求发送时的Cookie对象的数组
    Cookie[] cookies = request.getCookies();
    // 定义变量用于value的显示
    String username = "", password = "";
    // 判断获取来的cookie是否为空,不为空执行
    if (cookies != null) {
    
    
        // 遍历cookie数组里的数据
        for (Cookie cookie : cookies) {
    
    
           /* System.out.println(cookie.getName());
            System.out.println(cookie.getValue());*/
            // getName():获取Cookie名称(键),等于前端传来的username的值
            if (cookie.getName().equals("username")) {
    
    
                // getValue():获取Cookie的值,将值赋给变量username,用于后面value的显示
                username = cookie.getValue();
            }
            if (cookie.getName().equals("password")) {
    
    
                password = cookie.getValue();
            }
        }
    }
%>

<form action="registServlet" method="post">
                                                     <%-- =变量名:JSP中的语法,获取变量的值,显示到前端 --%>
    用户名:<input type="text" name="username" value="<%=username%>"> <br>
    密码:<input type="password" name="password" value="<%=password%>"> <br>
    <input type="submit" value="提交">
</form>
</body>
</html>

3. Cookie implementation displays the user’s last visit time

  • LastServlet.java

@WebServlet(name = "LastServlet", value = "/LastServlet")
public class LastServlet extends HttpServlet {
    
    
    @Override
    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
        boolean flag = false;   // 判断cookies是否为空
        // 访问过,cookies中会有时间
        if (cookies.length > 0 && cookies != null) {
    
         
            //遍历cookie数组
            for (Cookie cookie : cookies) {
    
    
                String name = cookie.getName();
                // 判断名称是否是lastTime
                if ("lastTime".equals(name)) {
    
    
                    // 有该cookie不是第一次访问
                    flag = true;     

                    // 响应数据与解码
                    String value = cookie.getValue();
                    value = URLDecoder.decode(value, "utf-8");
                    response.getWriter().write("欢迎回来,您上次访问的时间为:" + value);

                    cookie.setMaxAge(60 * 60 * 24 * 30);
                    response.addCookie(cookie);
                    break;
                }
            }

            if (cookies == null || cookies.length == 0 || flag == false) {
    
    

                // 获取系统时间与编码
                String str_date = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date());
                str_date = URLEncoder.encode(str_date, "utf-8");

                // 设置cookie的value
                Cookie cookie = new Cookie("lastTime", str_date);
                
                cookie.setMaxAge(60 * 60 * 24 * 30);
                response.addCookie(cookie);
                response.getWriter().write("您好,欢迎您首次访问");
            }
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doGet(request, response);
    }
}

4. Cookie encoding and decoding

Since Cookie does not support Chinese, we need to encode and decode it.

URLEncoder.encode("沈公子","utf-8");					// 编码
URLDecoder.decode(cookie.getValue(),"utf-8");		 // 解码

5. Cookie summary

  • cookie function
    • The cookie determines whether the user logs in for the first time. If it is the first time, he or she needs to log in. After the second time, he or she will access directly.
  • Cookie validity period setMaxAge();
    • If you close the browser without setting an expiration date, the cookie will be deleted.
    • Set the validity period to 0 and delete the cookie
    • Set the validity period, the cookie will be deleted after expiration
  • How to save cookies
    • A cookie can only save one piece of information
    • Cookies are saved by the browser

2.Session

1. Session overview

1.1. Introduction to Session

  1. Session objects are saved by the server.
  2. Session is a session tracking technology.
  3. Session is implemented based on Cookie.
  4. The server registers that you have come, and I will match you next time you come.
  5. Save the information and access it through SessionID, which will exist as soon as the browser is opened.
  6. The server will create a Session object for each user (browser).
  7. A Session occupies a browser. As long as the browser is not closed, this Session exists.
  8. After the user logs in, the entire website can be accessed, the user's information is saved, and the shopping cart information is saved.
  9. Share data between multiple requests in the same session.
    10. After the server is shut down, Tomcat will automatically write the Seesion data to the hard disk file. After starting the server again, it will load the data from the file into the Session.

1.2. Session usage scenarios

  • Save information for a logged in user
  • Shopping cart information
  • Data that is frequently used throughout the website, we save it in Session

1.3. The underlying principle of Session

Insert image description here

2. Basic use of Session

  1. getSession(): Get Session
  2. setAttribute(): Set key-value pair data for session
  3. getAttribute(): Get the value in the session through the key
  4. removeAttribute(): Remove the value in the session by key
  5. getId(): Get the session id
  6. invalidate(): The session is invalid. Entering again will reset the value of the Session.
  7. web.xml configures Session expiration time
<!--  设置Session默认的失效时间  -->
<session-config>
    <!-- 1分钟后Session自动失效,再次进入会重置Session的值,以分钟为单位 -->
    <session-timeout>1</session-timeout>
</session-config>
  • Test 1
@WebServlet(name = "SessionDemo01", value = "/SessionDemo01")
public class SessionDemo01 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取session
        HttpSession session = request.getSession();

        // 给session设置键值对数据
        session.setAttribute("name", "沈公子222");

        // 获取session的id (JSESSIONID=D2EBCA814B8FC3249BCA47C96374A2F8)
        String sessionId = session.getId();
        // 判断session是否已存在
        if (session.isNew()) {
    
    
            response.getWriter().write("session创建成功,ID:" + sessionId);
        } else {
    
    
            response.getWriter().write("session已经在服务器中存在,ID:" + sessionId);
        }

        // Session创建的时候做了什么事情,在响应中显示Cookie的值
        Cookie cookie = new Cookie("JSESSIONID", sessionId);
        response.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doGet(request, response);
    }
}
  • Test 2
@WebServlet(name = "SessionDemo02", value = "/SessionDemo02")
public class SessionDemo02 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取session
        HttpSession session = request.getSession();

        // 通过键获取session中的值
        Object name = session.getAttribute("name");

        response.getWriter().print(name);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doGet(request, response);
    }
}
  • Test 3
@WebServlet(name = "SessionDemo03", value = "/SessionDemo03")
public class SessionDemo03 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取session
        HttpSession session = request.getSession();

        // 通过键移除session中的值
        session.removeAttribute("name");

        // session失效,再次进入会重置Session的值
        session.invalidate();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doGet(request, response);
    }
}

3. Session login case

  • login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>

<form action="LoginServlet" method="post">
  用户名: <input type="text" name="username"><br/>
  密码: <input type="password" name="password"><br/>
  <input type="submit" value="提交">
</form>


</body>
</html>
  • User.java
public class User {
    
    
    private String username;
    private String password;

    public String getUsername() {
    
    
        return username;
    }

    public void setUsername(String username) {
    
    
        this.username = username;
    }

    public String getPassword() {
    
    
        return password;
    }

    public void setPassword(String password) {
    
    
        this.password = password;
    }
}
  • LoginServlet.java
@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (("root").equals(username) && ("123123").equals(password)) {
    
    
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            // 请求时获取Session,并将数据绑定进来
            request.getSession().setAttribute("user", user);
            response.sendRedirect(request.getContextPath() + "/IndexServlet");  // /demo06_3/IndexServlet
        } else {
    
    
            out.print("用户名或密码错误,登录失败,请重新登录<a href='/demo06_3/login.html'>返回登录</a>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doGet(request, response);
    }
}
  • IndexServlet.java
@WebServlet(name = "IndexServlet", value = "/IndexServlet")
public class IndexServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // 创建或者获取保存用户信息的Session对象
        HttpSession session = request.getSession();
        // 获取传递的数据
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
    
    
            out.print("您还没有登录,请<a href='/demo06_3/login.html'>登录</a>");
        } else {
    
    
            out.print("您已登录,欢迎你," + user.getUsername() + "!");
            out.print("<a href='/demo06_3/LogoutServlet'>退出</a>");
            // 创建Cookie存放Session的标识号
            Cookie cookie = new Cookie("JSESSIONID", session.getId());
            cookie.setMaxAge(60*30);  // 30分钟,session过期,需要重新登录
            // 设置Cookie的有效目录路径
            cookie.setPath(request.getContextPath());   // /demo06_3
            response.addCookie(cookie);
            // Set-Cookie: JSESSIONID=315710819A1A3518B0CCDCDC061BBD64; Max-Age=60; Expires=Wed, 22 Mar 2023 03:24:40 GMT; Path=/demo06_3
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doGet(request, response);
    }
}
  • LogoutServlet.java
@WebServlet(name = "LogoutServlet", value = "/LogoutServlet")
public class LogoutServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取Session时将Session对象中的User对象移除,并不是把Session的标识号给移除
        request.getSession().removeAttribute("user");
        response.sendRedirect(request.getContextPath()+"/IndexServlet");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doGet(request, response);
    }
}

4. Session shopping case

  • Cake.java
public class Cake {
    
    
    private String id;
    private String name;
    public Cake() {
    
    
    }
    public Cake(String id, String name) {
    
    
        this.id = id;
        this.name = name;
    }
    public String getId() {
    
    
        return id;
    }
    public void setId(String id) {
    
    
        this.id = id;
    }
    public String getName() {
    
    
        return name;
    }
    public void setName(String name) {
    
    
        this.name = name;
    }
}
  • CakeDB.java
public class CakeDB {
    
    
    private static Map<String,Cake> cake = new LinkedHashMap<>();
    static {
    
    
        cake.put("1",new Cake("1","A类蛋糕"));
        cake.put("2",new Cake("2","B类蛋糕"));
        cake.put("3",new Cake("3","C类蛋糕"));
        cake.put("4",new Cake("4","D类蛋糕"));
        cake.put("5",new Cake("5","E类蛋糕"));
    }
    // 获取所有的蛋糕
    public static Collection<Cake> getAll(){
    
    
        return cake.values();
    }
    // 根据指定的id获取蛋糕
    public static Cake getCake(String id){
    
    
        return cake.get(id);
    }
}
  • ListCakeServlet.java
@WebServlet(name = "ListCakeServlet", value = "/ListCakeServlet")
public class ListCakeServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // 获取所有蛋糕
        Collection<Cake> cakes = CakeDB.getAll();
        out.write("本站提供的蛋糕有:<br>");
        // 遍历输出所有蛋糕
        for (Cake cake : cakes) {
    
    
            // 获取蛋糕的id
            String url = "PurchaseServlet?id=" + cake.getId();
            // 获取蛋糕的名字和id,并跳转到 PurchaseServlet
            out.write(cake.getName() + "<a href='" + url + "'>点击购买</a><br>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doGet(request, response);
    }
}
  • PurchaseServlet.java
@WebServlet(name = "PurchaseServlet", value = "/PurchaseServlet")
public class PurchaseServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        // 这个 Servlet 起到中转的作用,用来判断是否购买蛋糕,根据情况来重定向
        String id = request.getParameter("id");
        // 如果id为空,将重定向到 ListCakeServlet
        if (id == null) {
    
    
            response.sendRedirect("ListCakeServlet");
            return;
        }
        Cake cake = CakeDB.getCake(id);     // 根据id获取蛋糕
        HttpSession session = request.getSession(); // 获取session
        List<Cake> cart = (List<Cake>) session.getAttribute("cart");  // 通过键获取session里的值
        // 如果session中的键的值为空,就创建列表,设置session数据
        if (cart == null) {
    
    
            cart = new ArrayList<>();
            session.setAttribute("cart", cart);
        }
        cart.add(cake); // 不等于空添加数据
        // session的设置
        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        cookie.setMaxAge(60 * 30);
        cookie.setPath("/Servlet");
        response.addCookie(cookie);
        response.sendRedirect("CartServlet");   // 有蛋糕会重定向 CarServlet
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doGet(request, response);
    }
}
  • CartServlet.java
@WebServlet(name = "CartServlet", value = "/CartServlet")
public class CartServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        List<Cake> cart = null;
        boolean purFlag = true; // 定义标识
        HttpSession session = request.getSession(false);
        // 如果session为空,标识为假
        if (session == null) {
    
    
            purFlag = false;
        } else {
    
        // session不为空
            // 通过键获取session里的值
            cart = (List<Cake>) session.getAttribute("cart");
            // 如果session中的键的值为空,标识为假
            if (cart == null) {
    
    
                purFlag = false;
            }
        }

        // 如果标识为假
        if (!purFlag) {
    
    
            out.write("对不起,您还没有购买任何商品!<br>");
        }else {
    
     // 否则标识为真
            out.write("您购买的蛋糕有:<br>");
            // 遍历输出蛋糕名称
            for (Cake cake : cart) {
    
    
                out.write(cake.getName()+"<br>");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doGet(request, response);
    }
}

5. Session summary

  • The role of Session
    • Save user information, shopping cart information, etc.
  • Session validity period
    • SessionID will exist as soon as the browser is opened. SeesionID will become invalid when the browser is closed.
    • Session expiration time can be configured
  • How to save session
    • Session saves data by the server
    • Session can save and obtain data

3. The difference between Session and Cookie

same:

  • Both Cookie and Session are used to share data between multiple requests in a session.

different:

  • Storage location: Cookie is stored on the client side, and Session is stored on the server side.
  • Security: Cookie is not safe, Session is safe
  • Data size: Cookie maximum 3KB, Session has no size limit
  • Storage time: Cookies can be stored for a long time, and Session defaults to 30 minutes.
  • Server performance: Cookies do not occupy server resources, and Sessions occupy server resources.

Guess you like

Origin blog.csdn.net/s17856147699/article/details/129518579