Cookie of Java Web session Technology

Keywords: Java Session encoding Tomcat less

Conversational Technology

  1. Session: multiple requests and responses in one session
    • One session: the browser sends a request to the server for the first time, and the session is established until one party disconnects
  2. Function: share data among multiple requests within the scope of one session
  3. Method:
    1. Client session Technology: Cookie
    2. Session: session
Cookie
  1. Concept: client session technology, saving data to client

  2. Quick start:

    • Use steps:
      1. Create Cookie object and bind data
        • new Cookie(String nameļ¼ŒString value)
      2. Send Cookie object
        • response.addCookie(Cookie cookie)
      3. Get cookies, get data
        • Cookie[] request.get
  3. Implementation principle

    • Implementation based on response header set cookie and request header cookie
  4. Cookie details

    1. Can I send multiple cookies at a time

      • Sure
      • You can create multiple cookie objects and use response to call addCookie method multiple times to send cookies
    2. How long does the Cookie stay in the browser

      • Default: Cookie data is destroyed when the browser is closed
      • Persistent storage
        • setMaxAge(int seconds)
          1. Positive: writes cookie data to a file on the hard disk. Persistent storage. Cookie lifetime
          2. Negative: default
          3. Zero: delete Cookie information
    3. Can cookies be saved in Chinese

      • Not supported before tomcat8
      • Support after tomcat8
    4. What is the scope of Cookie acquisition?

      1. If there are multiple web projects deployed in a tomcat server, can cookies be shared among these web projects
        • Cookie s cannot be shared by default
        • setPath (String path): set the scope of cookie acquisition. By default, sets the current virtual directory
          • If you want to share, you can set path to "/"
      2. Different Cookie sharing problems of tomcat server
        • setDomain(String path): if the primary domain name is the same, cookie s between multiple servers can be shared
          • setDomain (". Baidu. Com"), then cookies in tieba.baidu.com and news.baidu.com can be shared
    5. Characteristics and functions of cookies

      • Characteristic

        1. Cookies store data in client browser
        2. The browser has a limit on the size of a single cookie (4kb) and the total number of cookies under the same domain name (20)
      • Effect

        1. Cookies are generally used to store a small amount of less sensitive data
        2. Complete the server's identification of the client without logging in
    6. Case: remember last visit time

      1. Requirements:

        1. Visit a Servlet. If it's the first time, you will be prompted: Hello, welcome to visit for the first time
        2. If it is not the first visit, prompt: Welcome back, the last time you visited is: display time string
      2. Analysis

        1. Can be done with cookies
        2. The Servlet in the server determines whether there is a cookie named lastTime
          1. Yes: not the first visit
          2. No: first visit
            1. Response data: Hello, welcome to visit for the first time
            2. Write back cookie: lastTime=xxxxx
      3. Code

        public class CookieTest extends HttpServlet {
            @Override
            protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                //Set the data format and encoding of the message body of the response
                resp.setContentType("text/html;charset=utf-8");
                //1. Get all cookie s
                Cookie[] cookies = req.getCookies();
                boolean flag = false;//No cookie is lastTime
                //2. Traverse the cookies array
                if (cookies != null && cookies.length > 0){
                    for (Cookie cookie : cookies) {
                        //3. Get the name of the cookie
                        String name = cookie.getName();
                        //4. Judge whether the name is lastTime
                        if ("lastTime".equals(name)){
                            //This cookie is available, not the first time
                            flag = true; //Cookies with lastTime
                            //Set the value of the Cookie
                            //Get the string of the current time, reset the value of the cookie, and resend the cookie
                            Date date = new Date();
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy year mm month dd day HH:MM:SS");
                            String str_date = sdf.format(date);
                            System.out.println("Before coding"+str_date);
                            //URL encoding
                            str_date = URLEncoder.encode(str_date,"utf-8");
                            System.out.println("After coding"+str_date);
                            //Set cookie lifetime
                            cookie.setMaxAge(60*60*24*30);//one month
                            resp.addCookie(cookie);
                            //Response data
                            //Get the value of the cookie
                            String value = cookie.getValue();
                            System.out.println("Before decoding"+value);
                            value = URLDecoder.decode(value,"utf-8");
                            System.out.println("After decoding"+value);
                            resp.getWriter().write("<h1>Welcome back. Ning's last visit was:"+value+"</h1>");
                            break;
                        }
                    }
                }
        
                if(cookies == null || cookies.length == 0 || flag == false){
                    //No cookie s, first visit
                    //Set the value of the Cookie
                    //Get the string of the current time, reset the value of the cookie, and resend the cookie
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy year mm month dd day HH:MM:SS");
                    String str_date = sdf.format(date);
        
                    System.out.println("Before coding"+str_date);
                    //URL encoding
                    str_date = URLEncoder.encode(str_date,"utf-8");
                    System.out.println("After coding"+str_date);
        
                    Cookie cookie = new Cookie("lastTime",str_date);
                    //Set cookie lifetime
                    cookie.setMaxAge(60*60*24*30);//one month
                    resp.addCookie(cookie);
                    resp.getWriter().write("<h1>Hello, welcome to your first visit</h1>");
                }
            }
        
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                this.doPost(req,resp);
            }
        }
        
        

Posted by nakkaya on Sun, 03 May 2020 20:03:23 -0700