Cookie and Session Workflow

*TOC](Cookie and Session workflow)
Cookies are a mechanism for browsers to persistently store data locally.

What are cookies and sessions

1.Where does cookie data come from?
The server returns to the browser
2.Cookie data format
Cookies contain data in a key-value pair structure, and the key-value pairs here are all defined by programmers themselves.
3.What is the function of cookies?
Cookies can store some “temporary data” in the browser. One of the most typical ways is to store “identity identification”: sessionId. This involves the linkage between cookies and sessions. Cookie is the data stored by the browser (sessionId), and the session is the data stored by the server (storing the user’s detailed information and assigning a sessionId (unique value) to the user), and then visiting other pages of the website. When , the request will automatically bring the sessionId just now, and the server will know which user is currently operating.
4.Where do cookies go?
The content of the cookie will be automatically brought to the HTTP request the next time you visit the website.
5.How are cookies stored?
Browsers store cookies according to different “domain names”. Cookies between domain names cannot interfere with each other. Cookies stored on the hard disk often have a timeout period.

Core operations

Related methods in the HttpServletRequest class

Method Description
HttpSession getSession() Get the session from the server. If the parameter is true, a new session will be created if the session does not exist; if the parameter is false, null will be returned if the session does not exist
Cookie[]getCookies() Returns an array containing all Cookie objects sent by the client for this request. The format in the Cookie will be automatically parsed into key-value pairs

The getSession() method is the core API and has two effects:
1. If the current user does not have a session, a session will be created.
2. If you already have a session, you can query the session

Related methods in the HttpServletResponse class

Method Description
void addCookie(Cookie cookie) Add the specified cookie to the response.

Related methods in the HttpSession class

An HttpSession object contains multiple key-value pairs. We can store any information we need in the HttpSession

Method Description
Object getAttribute(Stringname) This method returns the object with the specified name in the session. If there is no object with the specified name, it returns null.
void setAttribute(Stringname, Object value ) This method uses the specified name to bind an object to the session session
boolean isNew() Determine whether the current It is a newly created session

The purpose of session is to allow users to store some customized data. The session here is more like a Map
There are many copies of session in the server. Each user has his own session. A server will have multiple users. Therefore, the server will also organize multiple sessions through Map.

Related methods in Cookie class

Each Cookie object is a key-value pair

Method Description
String getName() This method returns the name of the cookie. The name cannot be changed after creation. (This value is set to the browser by the SetCooke field)
String getValue() This method gets the value associated with the cookie
void setValue(StringnewValue) This method sets the value associated with the cookie.

What is stored in the HTTP Cooke field is actually multiple sets of key-value pairs. Each key-value pair corresponds to a Cookie object in the Servlet. By
HttpServletRequest.getCookies() obtains a series of Cookie key-value pairs in the request. Pass
HttpServletResponse.addCookie() can add new Cookie key-value pairs to the response.

setCookie

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;
@WebServlet("/setCookie")
public class setCookieServlet extends HttpServlet {<!-- -->
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {<!-- -->
        //Expect to return a custom cookie data to the browser through this doGet method
        Cookie cookie = new Cookie("data","2023-09-23");
        Cookie cookie1 = new Cookie("time","16:24");
        resp.addCookie(cookie);
        resp.addCookie(cookie1);
        resp.getWriter().write("setCookie ok");
    }
}

After running setCookie, the cookie will be constructed in the code and placed in the response. Through the fiddler packet capture tool, you can see that in the response of this request, there is

That is, the headers of these two responses are constructed by the addCookie operation in the code.
Set-Cookie: data=2023-09-23
Set-Cookie: time=16:24
Afterwards, through these two response headers, the cookie can be returned to the browser, and we can view the cookie attributes that have been set in the browser.

When a get request is sent again later, the cookie content will appear in the request.

getCookie

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;
@WebServlet("/getCookie")
public class getCookieServlet extends HttpServlet {<!-- -->
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {<!-- -->
        //Get the cookie in this request
        Cookie[]cookies = req.getCookies();
        if (cookies!=null){<!-- -->
            for (Cookie cookie:cookies){<!-- -->
                System.out.println(cookie.getName() + ":" + cookie.getValue());
            }
        }else{<!-- -->
            System.out.println("There is no cookie in the current request");
        }

        resp.getWriter().write("ok");
    }
}


At the same time, the server will also receive the cookie content returned by the browser.

Use cookies combined with session to achieve login effect

servlet also provides session-related support
To implement the login function, you do not need to use the cookie API directly, just use the session API directly.

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
</head>
<body>
    <form action="login" method="post">
        <input type="text"name="username">
        <input type="password"name="password">
        <input type="submit" value="Login">
    </form>
</body>
</html>

Here, an html page is constructed first. When the user clicks the submit button, a form form will be used to construct an http request. The method name is post and the path is login.

loginServlet

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/login")
public class loginServlet extends HttpServlet {<!-- -->
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {<!-- -->
        //1. Get username and password
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null||password==null||username.equals("")||password.equals("")){<!-- -->
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("The requested parameters are incomplete");
            return;
        }
        //2. Verify whether the username and password are correct
        if (!username.equals("zhangsan")){<!-- -->
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("Wrong username!");
            return;
        }
        if (!password.equals("88888888")){<!-- -->
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("Wrong password!");
            return;
        }
        //Login successful, now you can create a session for this user
        //The parameter is true, it will be created if it does not exist (used when logging in)
        //The parameter is false. If it does not exist, a null will be returned (used to jump to other pages later and check the user's login status)
        HttpSession session =req.getSession(true);
        //In the session, you can save customized data, such as saving a login timestamp.
        //The value after setAttribute is an object, any data can be stored
        session.setAttribute("username",username);
        session.setAttribute("time",System.currentTimeMillis());
        //4. Let the page automatically jump to the homepage of the website
        //It is agreed here that the path to jump to the homepage is index (servlet is also used to generate a dynamic page)
        resp.sendRedirect("index");

    }
}
Here is the logic about login. After successful login, the path of a new page is bound through redirection. The new path is index.

indexServlet

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//Generate a home page through this servlet
@WebServlet("/index")
public class indexServlet extends HttpServlet {<!-- -->
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {<!-- -->
        //Verify the user's login status first. If not logged in, the user is required to log in first.
        HttpSession session = req.getSession(false);
        if (session==null){<!-- -->
            //User is not logged in
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("Please log in first and then visit the homepage");
            return;
        }
        //Login successful
        //Get the previous attribute
        String username = (String) session.getAttribute("username");
        Long time = (Long) session.getAttribute("time");
        System.out.println("username=" + username + "time=" + time);
        //Construct a page based on this content
        resp.setContentType("text/html;charset=utf8");
        resp.getWriter().write("Welcome!" + username + "!Last login time:" + time);
    }
}