Java web learning notes (crazy version) -- Section 9 cookies and Session

If you are Xiaobai, this set of information can help you become a big bull. If you have rich development experience, this set of information can help you break through the bottleneck
2022web full set of video tutorial front-end architecture H5 vue node applet Video + data + code + interview questions.

Section 9 cookies and Session

catalogue

9.1 conversation

Session: users open a browser, click many hyperlinks, access multiple web resources, and close the browser. This process can be called session

Stateful session: a client has accessed the server, and the server will know that the client has accessed it next time

A website, how to prove that customers have visited? (client - > server)

  1. The server sends a letter to the client, and the client can bring the "letter" to the server next time - > cookie
  2. The server registers that the client has come. The next time the client accesses again, match - > session

Two techniques for saving sessions

cookie: a client technology (request and response)

Session: a server technology, which can be used to save the user's session information. We can put the information and data in the session

Common examples: after visiting a website, you can visit it directly without logging in next time

9.2 Cookie

  • Get cookie from request / / cookie [] cookie = req getCookies();
  • The server responds to the client Cookie / / resp addCookie(new Cookie(“lastLoginTime”,System.currentTimeMillis()+""));

Typical example: save the last access time of the user

//Save the time when the user last visited
public class cookie extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //The server tells you the time of arrival and encapsulates the time into a letter. The next time you bring a letter, the server will know you are coming
        req.setCharacterEncoding("utf-16");
        resp.setCharacterEncoding("utf-16");
        PrintWriter writer = resp.getWriter();
        //Cookie s are obtained by the server from the client
        Cookie[] cookies = req.getCookies();    //Returns an array indicating that there are multiple cookie s
        //First determine whether the Cookie exists
        if(cookies!=null){
            //If it exists
            writer.write("Your last visit was:");
            for(int i=0;i<cookies.length;i++){
                Cookie cookie = cookies[i];
                //Get the name of the cookie
                if(cookie.getName().equals("lastLoginTime")){
                    //Gets the value in the cookie
                    long l = Long.parseLong(cookie.getValue());
                    Date date = new Date(l);
                    writer.write(date.toLocaleString());
                }

            }
        }else {
            writer.write("This is your first visit to this site");
        }
        //The server responds with a cookie to the client
        resp.addCookie(new Cookie("lastLoginTime",System.currentTimeMillis()+""));
    }

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

Start test

If you close the browser, the time of the last visit will be changed and will not be saved. However, you can set the validity period to save the time of the last visit within the validity period, that is, the browser closes and the cookie still exists

//Cookies are valid for one day
cookie.setMaxAge(24*60*60);

Cookies are usually saved in the local user directory appdata

About Cookie deletion:

  • Do not set the validity period, close the browser and delete it automatically
  • Set the validity period to 0

Note: if there is Chinese in communication, it is best to use this method: urlencoding Encode ("Hello world", "utf-8"), decode urldecoder Decode ("Hello world", "utf-8")

9.3 Session

Session Introduction: the server will create a session object for each user (browser). A session monopolizes a browser, that is, as long as the browser is not closed, the session will exist

After the user logs in, the whole website can be accessed – > save user information (save shopping cart, etc.)

Typical example: get the information of a class through session

Access / session storage information

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Solve the problem of garbled code
        req.setCharacterEncoding("utf-16");
        resp.setCharacterEncoding("utf-16");
        resp.setContentType("text/html;charset=utf-8");
        //Get Session
        HttpSession session = req.getSession();

        //Store data for session
        session.setAttribute("name",new person("srq",520));
        //Get the id of the session
        String id = session.getId();

        //Determine whether it is a new session
        if(session.isNew()){
            resp.getWriter().write("new session Created, new session of id For:"+id);
        }else {
            resp.getWriter().write("session Existing, new session of id For:"+id);
        }
        //What was done when the Session was created
//        Cookie cookie = new Cookie("JSESSIONID",id);
//        resp.addCookie(cookie);
    }

Access / s2 print information

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Solve the problem of garbled code
        req.setCharacterEncoding("utf-16");
        resp.setCharacterEncoding("utf-16");
        resp.setContentType("text/html;charset=utf-8");
        //Get Session
        HttpSession session = req.getSession();
        //Get Session data
        person name = (person) session.getAttribute("name");
        System.out.println(name.toString());
    }

Start test

Session logout:

Unregister in java file

session.invalidate();

Log off in profile

<!--  set up Session Default expiration time of-->
  <session-config>
    //The session will automatically fail after 15min
    <session-timeout>15</session-timeout>
  </session-config>

The difference between Session and Cookie:

Cookie: write the user's data to the user's browser (save multiple information)

Session: write the user's data in the user's exclusive session (save important information) and create it by the server

Usage scenario: save user login information and shopping cart information


If the article is helpful to you, remember to support it with one key and three links~

Keywords: Javascript Front-end Mini Program

Added by Boris Senker on Sun, 20 Feb 2022 12:23:10 +0200