Java web learning notes ----- Cookie, Session

Posted by techbinge on Wed, 05 Jan 2022 15:12:42 +0100

Java web learning notes (V) -- Cookie, Session

conversation

  • Session: users open a browser, click many hyperlinks, access multiple web resources, and close the browser. This process can be called session
  • Stateful conversation: a classmate has come to the teacher. Next time, we will know that this classmate has come. This is called stateful dialogue.

How does a website prove you've been here

  • Client and client
  • The server gives the client a message (cookie), and the client can bring the message to the server next time
  • You've been here. I'll match you next time you come

Two techniques for saving sessions

Cookie

  • Client Technology (response, request)

Session

  • Server technology. Using this technology, we can save the user's Session information. We can put the information or data in the Session.

Common cases

  • After you log in to the website, you don't need to log in again for the second time. You can log in directly

Cookie

  • Get Cookie information from the request

  • The server responds to the client

    //Save the time the user last visited
    public class CookieDemo01 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //The server tells you the time of arrival, encapsulates the time into a letter, and brings it next time, you'll know you're here
            //Solve Chinese garbled code
            resp.setContentType("text/html");
            req.setCharacterEncoding("utf-8");
            resp.setCharacterEncoding("utf-8");
            PrintWriter out = resp.getWriter();
            //Cookie, which is obtained by the server from the client
            Cookie[] cookies = req.getCookies();  //An array is returned here, indicating that there may be multiple cookies
            //Determine whether the Cookie exists
            if(cookies!=null){
                //What if it exists
                out.write("Last visited:");
                for (int i = 0; i < cookies.length; i++) {
                    Cookie cookie = cookies[i];
                    //Gets the name of the Cookie
                    if(cookie.getName().equals("time")){
                        //Gets the value in the Cookie
                        long l = Long.parseLong(cookie.getValue());
                        Date date = new Date(l);
                        out.write(date.toLocaleString());
                    }
                }
            }else{
                out.write("This is your first visit to this site");
            }
            //When the client responds to a cookie, it can new whatever parameters it needs
            Cookie cookie = new Cookie("time", System.currentTimeMillis()+"");
            //Set the cookie to be valid for 1 day
            cookie.setMaxAge(24*60*60);
            resp.addCookie(cookie);
    
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
  • cookie: usually saved in the local user directory, appdata

Is there an upper limit for a website cookie

  • A cookie can only hold one piece of information
  • A web site can send multiple cookies to the browser. The upper limit of the browser is about 300. A site can store up to 200 cookies
  • The cookie size is limited to 4kb

Delete Cookie

  • If the validity period is not set, the browser will automatically become invalid after closing
  • Set the validity time to 0
public class CookieDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Create a cookie with the same name as the one to be deleted
        Cookie cookie = new Cookie("time",System.currentTimeMillis()+"");
        //Set cookie validity to 0
        cookie.setMaxAge(0);
        resp.addCookie(cookie);
    }

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

Encoding and decoding

URLDecoder.decode(cookie.getValue(),"utf-8");
URLEncoder.encode("Zhang","utf-8");

Session (key)

What is a Session:

  • The server will create a Session object for each user (browser)
  • A Session monopolizes a browser. As long as the browser is not closed, the Session exists
  • After the user logs in, the whole website can be accessed, similar to logging in to CSDN
public class SessionDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Solve the problem of garbled code
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        //Get Session
        HttpSession session = req.getSession();
        //Save something in the Session
        session.setAttribute("name",new Person("Zhang Zhang",18));
        //Gets the ID of the session
        String id = session.getId();
        //Judge whether the Session is newly created
        if(session.isNew()){
            resp.getWriter().write("session Created successfully, ID: "+id);
        }else{
            resp.getWriter().write("session Already exists on the server, ID: "+id);
        }

        //What was done when the session was created

    }

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

Delete session

  • Manually unregister session
public class SessionDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.removeAttribute("name");
        //Manually unregister session
        session.invalidate();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
  • On the web Set the default expiration time of session in XML
  <!--set up session Default expiration time-->
  <session-config>
    <!--15 Minutes later session Automatic failure-->
    <session-timeout>15</session-timeout>
  </session-config>
  • When the browser cleans up the cache, you can check clean session

Usage scenario

  • Save the information of a logged in user
  • Shopping cart information
  • In the whole website, we often use the data, and we save it in the session

The difference between Session and Cookie

  • Cookie is to write the user's data to the user's browser, and the browser saves it (the client can save multiple)
  • Session is to write the user's data to the user's exclusive session and save it by the server (save important information and reduce the waste of server resources)
  • The Session object is created by the server

Topics: Session cookie