Java Web cookies and sessions

Conversation introduction

  • Session: multiple requests and responses between browser and server
  • In order to realize some functions, multiple requests and responses may be generated between the browser and the server, from the browser accessing the server to the end of accessing the server (closing the browser and expiration time). The multiple requests and responses generated during this period are called a session between the browser and the server.
  • Some data generated during the Session can be saved through Session Technology (Cookie and Session).

Cookie

  • Cookie: client session management technology. Save the data to be shared to the client. At each request, the session information is brought to the server, so as to realize the data sharing of multiple requests!
  • Function: it can save the relevant contents of the website accessed by the client, so as to ensure that each access is obtained from the local cache first, so as to improve efficiency!

Cookie properties

Attribute nameeffectIs it important
nameThe name of the CookieRequired attribute
valueValue of Cookie (Chinese is not supported)Required attribute
pathPath to Cookieimportant
domainThe domain name of the Cookieimportant
maxAgeCookie lifetimeimportant
versionThe version number of the Cookieunimportance
commentDescription of the Cookieunimportance

Cookie method

Method nameeffect
Cookie(String name,String value)Creating objects using construction methods
set and get methods corresponding to propertyAssign and get values

Cookie addition and acquisition

  • Add: HttpServletResponse
    Return valueMethod nameexplain
    voidaddCookie(Cookie cookie)Add cookies to clients
  • Add: HttpServletRequest
    Return valueMethod nameexplain
    Cookie[]getCookie(Cookie cookie)Get all cookies

Use of cookies

  • Requirement Description: record the last access time through Cookie and display it on the browser.
  • Ultimate goal: master the use of cookies, from creating to adding clients, and then obtaining from the server.
package cn.liu.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;


@WebServlet("/newServlet")
public class ServletDemo02 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        // 1. Write the prompt information through the response object
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = resp.getWriter();
        pw.write("Welcome to this website. Your last visit time is:<br>");

        // 2. Create a Cookie object to record the last access time
        Cookie cookie = new Cookie("time",System.currentTimeMillis()+"");

        // 3. Set the maximum survival time
        cookie.setMaxAge(3600);

        // 4. Add Cookie object to client
        resp.addCookie(cookie);

        // 5. Get cookies
        Cookie[] arr = req.getCookies();
        for (Cookie c:arr){
            if ("time".equals(c.getName())){
                //6. Get the value in the cookie object and write it
                String value = c.getValue();
                SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                pw.write(sdf.format(new Date(Long.parseLong(value))));
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        doGet(req,resp);
    }
}

cookie details

  • Quantity limit
    Each website can have up to 20 cookies with a size of 4KB. All websites cannot be more than 300
  • Name restrictions
    • The name of the Cookie can only contain alphanumeric characters in the ASCCI table. Cannot contain commas, semicolons, spaces, or start with $.
    • The value of the Cookie does not support Chinese.
  • The lifetime limit setMaxAge() method accepts numbers
    • Negative integer: the current session is valid and cleared when the browser is closed.
    • 0: clear now
    • Positive integer: sets the survival time in seconds.
  • Access path restrictions
    • Default path: it is obtained from the resource path prefix accessed for the first time. As long as it starts with this prefix (including child paths), it can be obtained, otherwise it can not be obtained

      • For example:
        • /liu/qwe setting cookies
        • /liu/asd can get
        • /liu/zxc/weq can get
        • /xiu/qwe failed to get
    • Set path: the setPath() method sets the specified path

Session

Introduction to HttpSession

  • HttpSession: server-side session management technology
    • The essence is to use client session management technology.
    • Only a special ID is saved on the client side, and the shared data is saved to the memory object on the server side.
    • Each time a request is made, a special ID will be brought to the server, and the corresponding memory space will be found according to this ID, so as to realize data sharing!
    • Session domain object is one of the four domain objects in Servlet specification
  • Function: data sharing can be realized
    Domain objectfunctioneffect
    ServletContextApplication domainData sharing across applications
    ServletRequestRequest domainData sharing between current requests or request forwarding
    HttpSessionSession domainData sharing between current session scopes

HttpSession common methods

Return valueMethod nameexplain
voidsetAttribute(String name,Object value)Set up shared data
ObjectgetAttribute(String name)Get shared data
voidremoveAttribute(String name)Delete shared data
StringgetId()Get unique identification name
voidInvalidate()Let the session fail immediately

HttpSession get

Return valueMethod nameexplain
HttpSessiongetSession()Get HttpSession object
HttpSessiongetSession(boolean create)The HttpSession object was obtained, but it was not obtained whether to create it automatically

Use of HttpSession

  • Requirement Description: set the shared data user name through the first Servlet and obtain it in the second Servlet.
  • Ultimate purpose: master the basic use of HttpSession and how to obtain and use it.
package cn.liu.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;


@WebServlet("/newServlet")
public class ServletDemo02 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        // 1. Get the requested user name
        String username = req.getParameter("username");

        // 2. Get the object of HttpSession
        HttpSession session = req.getSession();

        // 3. Add user name information to the shared data
        session.setAttribute("username",username);


        /*---------------- This is the ServletDemo01 class------------------*/
        // 1. Get HttpSession object
        HttpSession session1 = req.getSession();

        // 2. Obtain shared data
        Object username1 = session1.getAttribute("username");

        // 3. Respond the data to the browser
        resp.getWriter().write(username1+"");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        doGet(req,resp);
    }
}

Details of HttpSession

  • View the unique ID (you can see it in the Cookie with the developer tool)
  • The browser disables cookies (all session technologies will be invalidated (including cookies and sessions))
    • resolvent:
      • Prompt the user not to disable (implemented in JavaScript, this is recommended)
      package cn.liu.servlet;
      
      import javax.servlet.ServletException;
      import javax.servlet.annotation.WebServlet;
      import javax.servlet.http.*;
      import java.io.IOException;
      
      @WebServlet("/newServlet")
      public class ServletDemo02 extends HttpServlet {
      
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
      
              /*---------------- This is the ServletDemo01 class------------------*/
              // 1. Get HttpSession object
              HttpSession session1 = req.getSession();
              if (session1 == null){
                  resp.setContentType("text/html;charset=UTF-8");
                  resp.getWriter().write("In order not to affect normal use, please do not disable the browser Cookie");
              }
      
          @Override
          protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
              doGet(req,resp);
          }
      }
      
      • Put the Session ID into the browser variable (not good, splice the Session ID) (not recommended)
      • Implementing url rewriting is equivalent to splicing a sessionid behind the address bar (not recommended)
      package cn.liu.servlet;
      
      import javax.servlet.ServletException;
      import javax.servlet.annotation.WebServlet;
      import javax.servlet.http.*;
      import java.io.IOException;
      
      
      @WebServlet("/newServlet")
      public class ServletDemo02 extends HttpServlet {
      
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
              // 1. Get the requested user name
              String username = req.getParameter("username");
      
              // 2. Get the object of HttpSession
              HttpSession session = req.getSession();
      
              // 3. Add user name information to the shared data
              session.setAttribute("username",username);
      
              // Implementing url rewriting is equivalent to splicing a sessionid behind the address bar
              resp.getWriter().write("<a href='"+resp.encodeURL("http://localhost:8080/jsp_test_war_exploded/newServlet") +"'>go ServletDemo01</a>");
          }
      
          @Override
          protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
              doGet(req,resp);
          }
      }
      
  • Passivation and activation
    • What is passivation and activation
      • Passivation: serialization. Serialize the HttpSession that has not been used for a long time but has not expired, and write it on disk
      • Opposite state
    • When to passivate
      • The first case: when the traffic is large, the server will serialize the HttpSession that has not been used for a long time but has not expired according to getLastAccessTime.
      • The second case: when the server restarts, it should also be serialized to protect the data in the client HttpSession.
    • Note: the serialization of HttpSession is automatically completed by the server. We don't need to care

Tags: Java http

Posted on Sun, 12 Sep 2021 21:56:56 -0400 by Snake PHP