Let’s talk again: Cookies and Sessions

Table of Contents

1: Cookies

1:What are cookies?

2: Where does cookie data come from?

3:What does the cookie data look like?

4:The role of cookies

5:Where do cookies go?

6: How to save cookies?

2: Practical operation

2.1: Cookie operation

2.1.1:HttpServletRequest

2.1.2:HttpServletResponse

2.1.3: Implementation case

2.2:Session operation

2.1.1:HttpServletRequest

2.1.2:HttpSession

2.1.3: Login case implementation


一:Cookie

1:What is Cookie?

Cookie: It is a mechanism for the browser to store data locally and persistently.

Cookie data is returned to the browser by the browser.

Cookies contain data in key-value pairs, and the data in these key-value pairs are customized by programmers.

4:The role of cookies

Cookies can store temporary data on the browser, which is used to store “identity identifiers”. The identity identifier here is equivalent to sessionId.

The content in the cookie will be automatically brought to the http request the next time you visit the website.

6:How to save cookies?

Browsers store cookies according to different “domain names”. The cookies between domain names are different.

Cookies are stored on your hard drive. Cookies often have timeouts.

Two: Practical Operations

Combined with Servlet, further perform some practical operations on Cookie and Session.

2.1:Cookie operation

2.1.1:HttpServletRequest

Static method provided by HttpServletRequest: Cookies[] getCookies(): obtains the contents of all Cookies.

Each element is equivalent to a cookie object, which contains the corresponding key-value pair. At the same time, each cookie object has three static methods:

Method Description
String getName() Get the cookie name
String getValue() Get the cookie Value
void setValue(String newValue) Set the value of the new cookie

2.1.2:HttpServletResponse

Since the HttpServletResponse class calculates the response based on the request, the method provided is to add cookies to the response.

void addCookie(Cookie cookie) Specify Cookies are added to the response

2.1.3:Implementation Case

Use the static method addCookie provided by HttpServletResponse to add the corresponding cookie (at the same time, add it to the response and add it to set-cookie)

Use the static method provided by HttpServletRequest, getCookies, to get the array and print each content of the array cookie object.

@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 the doGet method
       resp.addCookie(new Cookie("date","2023-09-23"));
       resp.addCookie(new Cookie("username","lmx"));
       resp.addCookie(new Cookie("password","1234"));
       resp.getWriter().write("setCookie ok");

    }


}
@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();
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName() + ":" + cookie.getValue());
        }
        resp.getWriter().write("ok");
    }
}

operation result:

2.2:Session operation

2.1.1:HttpServletRequest

HttpSession getSession()

1: If the user does not currently have a session, a sessionID will be created.

2: If the user has a session, directly obtain the corresponding session

2.1.2:HttpSession

Object getAttribute(String name) 1
void sertAttritube(String name,Object value) 2
boolean isNew() 3

1: Get the corresponding value based on name

2: Set the corresponding name and value values

3: Determine whether a new session is created

Further explanation of the above picture: The server will Save the sessionId of multiple users, that is, the client saves its own sessioID. The server obtains the sessionID of each client, obtains the value corresponding to each user, that is, attritube, and then obtains the multiple values in it.

2.1.3: Login case implementation

Login code:

@WebServlet("/login")
public class loginServlet extends HttpServlet {
    @Override
    protected void doGet(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 current request parameters are incomplete");
            return ;
        }
        //Verify that the username and password are correct. The legal user is zhangsan and the password is 123.
        if(!username.equals("zhangsan")){
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("The current username is wrong");
            return ;
        }
        if(!password.equals("123")){
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("Wrong password");
            return ;
        }
        //The login is successful. At this time, can you create a session painting for this user?
        HttpSession session = req.getSession(true);

        session.setAttribute("username",username);
        session.setAttribute("time", System.currentTimeMillis());
        System.out.println(session.getAttribute("password"));
        //4: Let the page automatically jump to the page, using the redirection of resp
        resp.sendRedirect("index");
    }

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

Home page code:

@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 it does not exist, null will be returned.
        HttpSession session = req.getSession(false);
        if(session==null){
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("The user is not logged in, please log in first and then visit the homepage");
        }
        //You have logged in successfully, take out the previous painting
       String username = (String) session.getAttribute("username");
       long time= (long) session.getAttribute("time");
       String password = (String) session.getAttribute("password");
        System.out.println("Username: " + username + "Password: " + password + " Timestamp: " + time);
        resp.setContentType("text/html; charset=utf8");
        resp.getWriter().write("Welcome, " + username + "! Last login time: " + time);


    }
}

login.html static page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
   <form action="1" method="post">
      Name:<input type="text" name="username">
       <br>
      Password:<input type="password" name="password">
       <br>
       <input type="submit" value="Login">
   </form>
</body>
</html>

operation result:

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 136342 people are learning the system