Web project development practice, Cookie and Session mechanism

Posted by Cook on Wed, 08 Dec 2021 21:00:17 +0100

Session tracking is a common technology in Web programs, which is used to track the whole session of users. The commonly used session tracking technologies are cookie and session. Cookie determines the user identity by recording information on the client, and session determines the user identity by recording information on the server. This chapter will systematically describe the cookie and session mechanisms, and compare and explain when cookie and session cannot be used.

All the source code of this chapter is included in the project Session.

5.1 cookie mechanism

Session tracking is very important in programs. Theoretically, all request operations of one user should belong to the same session, while all request operations of another user should belong to another session. The two cannot be confused. For example, any commodity purchased by user a in the supermarket should be placed in the shopping cart of user A. no matter when user a purchases it, it belongs to the same session and cannot be placed in the shopping cart of user B or user C. It does not belong to the same session.

Web applications use the HTTP protocol to transfer data. HTTP protocol is a stateless protocol. Once the data exchange is completed, the connection between the client and the server will be closed. A new connection needs to be established to exchange data again. This means that the server cannot track sessions from the connection. That is, user a purchases a commodity and puts it into the shopping cart. When purchasing the commodity again, the server can no longer judge whether the purchase behavior belongs to the session of user a or the session of user B. To track this session, a mechanism must be introduced.

Cookie is such a mechanism. It can make up for the lack of stateless HTTP protocol. Before Session, almost all websites used cookies to track sessions.

5.1.1 what is a Cookie

Cookie, which means "cookie", is a mechanism proposed by W3C and first developed by Netscape community. At present, cookies have become the standard, and all mainstream browsers such as IE, Netscape, Firefox, Opera, etc. support cookies.

Because HTTP is a stateless protocol, the server cannot know the identity of the client from the network connection alone. What shall I do? Just issue a pass to the clients, one for each person. No matter who visits, they must carry their own pass. In this way, the server can confirm the customer's identity from the pass. This is how cookies work.

A Cookie is actually a short piece of text information. The client requests the server. If the server needs to record the user status, it uses response to issue a Cookie to the client browser. The client browser saves the Cookie. When the browser requests the website again, the browser submits the requested URL to the server together with the Cookie. The server checks the Cookie to identify the user status. The server can also modify the contents of the Cookie as needed.

It's easy to view cookies issued by a website. Just enter javascript:alert (document. cookie) in the browser address bar. The JavaScript script will pop up a dialog box to display the contents of all cookies issued by the website, as shown in Figure 5.1.

Figure 5.1 cookies issued by Baidu website

In the pop-up dialog box in Figure 5.1, the cookies of Baidu website are displayed. The first line of BAIDUID records the author's identity helloweenvsfei, but Baidu uses a special method to encrypt the Cookie information.

%Note: the Cookie function requires the support of the browser. If the browser does not support Cookies (such as browsers in most mobile phones) or disables Cookies, the Cookie function will fail. Different browsers save Cookies in different ways. The IE browser will save as a text file in the folder "C:\Documents and Settings \ your user name \ Cookies". One text file will save one Cookie.

5.1.2 record user access times

In Java, cookies are encapsulated into javax.servlet.http.Cookie class. Each Cookie is an object of this Cookie class. The server operates on client cookies by operating Cookie class objects. Obtain all cookies submitted by the client through request.getCookie() (returned in the form of Cookie [] array), and set cookies to the client through response.addcookie (Cookie).

Cookie objects use key value attribute pairs to save user status. A cookie object saves an attribute pair, and a request or response uses multiple cookies at the same time. Because the cookie class is located under the package javax.servlet.http. *, it is not necessary to import this class in JSP.

Look at an example of using cookies to record user accounts and login times. Create a new Web Project in MyEclipse, select Java EE 5.0 specification, and fill in the project name sessionWeb. Create a new JSP page cookie.jsp. The input source code is as follows:

Code 5.1 cookie.jsp

<%@ page language="java"pageEncoding="UTF-8" errorPage="login.jsp" %>
<%
   request.setCharacterEncoding("UTF-8");             // Set request encoding
    String username ="";                             // user name
    int visitTimes = 0;                               // Number of visits
    Cookie[] cookies =request.getCookies();           // All cookies 
    for(int i=0;cookies!=null&&i<cookies.length; i++){
                                          // Traverse the Cookie to find the account and login times
        Cookie cookie =cookies[i];         // The ith Cookie
       if("username".equals(cookie.getName())){// If the Cookie name is username
           username = cookie.getValue();       // The contents of the Cookie are recorded
        }
        elseif("visitTimes".equals(cookie.getName())){
                                          // If the Cookie name is visitTimes
           visitTimes = Integer.parseInt(cookie.getValue());
                                          // The contents of the Cookie are recorded
        }
    }
    if(username == null ||username.trim().equals("")){
                                          // If the user name is not found, go to the login interface
        throw newException("You haven't signed in yet. Please log in first");
    }
    // Modify the Cookie to update the user's access times
    Cookie visitTimesCookie = newCookie("visitTimes", Integer.toString 
    (++visitTimes));
   response.addCookie(visitTimesCookie);   // Overwrite Cookie named visitTimes
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01Transitional//EN">
<html>
<body>
<div style="margin:10px; ">
    <fieldset>
        <legend>login information</legend>
        <formaction="login.jsp" method="post">
            <table>
               <tr>
                   <td>Your account number:</td>
                   <td><%= username%></td>
               </tr>
               <tr>
                   <td>Login times:</td>
                   <td><%= visitTimes%></td>
               </tr>
               <tr>
                   <td></td>
                   <td>
                       <inputtype="button" value=" Refresh " onclick= 
                       "location='<%=request.getRequestURI() %>?ts=' + 
                       new Date().getTime(); "class="button">
                   </td>
               </tr>
            </table>
        </form>
    </fieldset>
</div>
</body>
</html>

The program uses cookies to record the number of user visits. If the user does not log in, the login interface is displayed. The working principle is that the program checks the Cookie first. If the Cookie containing the username attribute is not found, an exception will be thrown, and the page will jump to the error handling page login.jsp specified in errorPage. The source code of login.jsp is as follows:

Code 5.2 login.jsp

<%@ page language="java"pageEncoding="UTF-8" isErrorPage="true" %>
<%
   request.setCharacterEncoding("UTF-8");      // Set request encoding method
   response.setCharacterEncoding("UTF-8"); // Set the response encoding method
   if("POST".equals(request.getMethod())){ // If you log in through POST
        CookieusernameCookie =                // Create a new Cookie named username
        newCookie("username", request.getParameter("username"));
        CookievisittimesCookie = new Cookie("visitTimes", "0");
                                              // New Cookie
       response.addCookie(usernameCookie); // Add to response
       response.addCookie(visittimesCookie);   // response sends the Cookie
 To client
       response.sendRedirect(request.getContextPath() +"/cookie.jsp");    // Show Cookie page
        return;
    }
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01Transitional//EN">
<html>
<head>
<title>Please log in first</title>
<link rel="stylesheet"type="text/css" href="css/style.css">
</head>
<body>
<div style="margin:10px;">
    <fieldset>
        <legend>Sign in</legend>
        <formaction="login.jsp" method="post">
           <table>
               <tr>
                   <td></td>
                   <td><span><imgsrc="images/errorstate.gif"></span>
                       <spanstyle="color:red; "><%= exception.get 
                       Message() %></span></td>
               </tr>
               <tr>
                   <td>account number: </td>
                   <td><input type="text"name="username" style="width: 
                   200px; "></td>
               </tr>
               <tr>
                   <td>password: </td>
                   <td><inputtype="password" name="password" style= 
                   "width:200px; "></td>
               </tr>
               <tr>
                   <td></td>
                   <td><inputtype="submit" value=" Sign in " class= 
                   "button"></td>
               </tr>
           </table>
        </form>
    </fieldset>
</div>
</body>
</html>

The running effect of the program is shown in Figure 5.2.

Figure 5.2 using cookies to record user visits

Both client a and client B may access the program. A will submit a's Cookie and B will submit B's Cookie. The code request.getCookies() does not indicate who gets the Cookie. Whose Cookie is this code taking? The answer is that a takes a's Cookie when executing, and B takes B's Cookie when executing. This is stipulated by the Cookie mechanism. The program only needs to simply execute request.getCookies(). The server will only return the cookies of the current customer, not those of other customers. The cookies of each client are independent and invisible to each other.