Cookie of Java Session Technology

Cookie of Java Session Technology

@[TOC]

1 Conversation technology

1.1 Overview of Session Management

1.1.1 What is a session

The session here refers to a call process in web development. When the browser is opened and the website address is accessed, the session starts. When the browser is closed (or the expiration time is reached), the session ends.

for example:

For example, you are calling a family member, and suddenly the courier delivering the courier knocks on the door. You put down the phone and open the door. After receiving the courier, the call is still on hold, so just keep talking.

1.1.2 The role of session management

When will session management be used? The most common is the shopping cart. When we log in successfully, we add products to the shopping cart. At this time, no matter what products we browse, when we click on the shopping cart, those added products are still in the shopping cart.

In our actual development, there are still many places where session management technology is inseparable. For example, if we post on the forum, visitors who are not logged in are not allowed to post. So when we log in successfully, no matter which section we enter to post, as long as the permissions allow, the server will recognize us and let us post, because the information of successful login is always kept in the server-side session.

Through the above two examples, we can see that it is used for us to share data, and to achieve data sharing between different requests. In other words, if we need to realize data sharing between multiple requests, we can consider using session management technology.

1.1.3 Session Management Classification

In JavaEE projects, session management is divided into two categories.

They are:

  • Client session management technology
  • Server-side session management technology.

Client session management technology (cookie)

It saves the data to be shared on the client side (that is, the browser side). Each time a request is made, the session information is brought to the server, thereby realizing data sharing for multiple requests.

Server-side session management technology (session)

Its essence is still the use of client-side session management technology, but it is a special identifier that is saved to the client, and the data to be shared is saved in the memory object of the server.

Each time a request is made, this identifier is brought to the server side, and then this identifier is used to find the corresponding memory space to realize data sharing.

1.2 Client session management technology

1.2.1 Overview of Cookies

1) What is Cookie

==It is a cache file of the client browser, which records some content of the website visited by the client browser==. (See what is stunned later, and then look at this sentence, he is a cache file, what it does, it saves things)

At the same time, it is also part of the HTTP protocol request and response message headers (in the HTTP protocol course, we noted that it is very important).

2) Detailed API of Cookie

effect

It can save the relevant content of the website visited by the client's browser (requires the client to not disable cookies).

Therefore, when the same content is needed for each visit, it is first obtained from the local cache, so that resources are shared and efficiency is improved.

We can also disable cookies from the developer console

Cookie properties

Attribute nameAttribute roleIs it important
namethe name of the cookieRequired attributes
valuecookie value (cannot be Chinese)Required attributes
pathcookie pathimportant
domaincookie domainimportant
maxAgeThe lifetime of the cookie.important
versionThe version number of the cookie.unimportant
commentThe description of the cookie.unimportant

cookie details

Cookies are limited in size and number. Each website can only store up to 20 cookies, and the size cannot exceed 4kb. At the same time, the total number of cookies on all websites does not exceed 300.

When deleting cookies, set the maxAge value to 0. When maxAge is not set, the memory of the browser is used. When the browser is closed, the cookie will be lost. If this value is set, it will be saved as a cache file (the value must be greater than 0, in seconds).

3) Common methods involved in Cookie

All cookie methods

Create cookie

The following figure is the prototype of the cookie construction method

public Cookie (String name, String value) { if (name != null && name.length() != 0 ) { if ( this .isToken(name) && !name.equalsIgnoreCase( "Comment" ) && !name.equalsIgnoreCase ( "Discard" ) && !name.equalsIgnoreCase( "Domain" ) && !name.equalsIgnoreCase( "Expires" ) && !name.equalsIgnoreCase( "Max-Age" ) && !name.equalsIgnoreCase( "Path" ) && !name .equalsIgnoreCase( "Secure" ) && !name.equalsIgnoreCase( "Version" ) && !name.startsWith( "$")) { this .name = name; this .value = value; } else { String errMsg = lStrings.getString( "err.cookie_name_is_token" ); Object[] errArgs = new Object[]{name}; errMsg = MessageFormat.format(errMsg, errArgs); throw new IllegalArgumentException(errMsg); } } else { throw new IllegalArgumentException(lStrings.getString( "err.cookie_name_blank" )); } } Copy code

According to the above general idea, it can be simplified to this

/** * Construct a Cookie with the specified name and value * * The name of the cookie must follow the RFC 2109 specification. This means that it can only contain ASCII alphanumeric characters, * Cannot contain commas, semicolons or spaces or start with a $ character. * The name of the cookie cannot be changed after creation. * * This value can be anything the server chooses to send. * Its value may only be of interest to the server. * After creation, you can use the setValue method to change the value of the cookie. */ public Cookie (String name, String value) { validation.validate(name); this .name = name; this .value = value; } Copy code

Add cookies to the browser

/** * Add Cookie to the response. This method can be called multiple times to add multiple cookies. */ public void addCookie (Cookie cookie) ; Copy code

Get cookies from the server

/** * This is the method in HttpServletRequest. * It returns an array of Cookies, including all the Cookie objects sent by the client with this request. * If there is no cookie that meets the rules, this method returns null. */ public Cookie[] getCookies(); Copy code

1.2.2 Cookie case

1) Demand description

Create a cookie, set the path of the cookie, and access it through different paths, so as to check how the request carries the cookie.

2) The purpose of the case

Through the explanation of this case, students can clearly describe when the client browser brings the cookie to the server side and when not.

3) Case steps

The first step: create a JavaWeb project

Just use the project in the first case.

Step 2: Write Servlet

/** * Cookie path problem * Preliminary preparation: * 1. Write a cookie to the client in demo1 * 2. Get cookies in demo2 and demo3 respectively * The Servlet mapping of demo1 is/servlet/PathQuestionDemo1 * The Servlet mapping of demo2 is/servlet/PathQuestionDemo2 * The Servlet mapping of demo3 is/PathQuestionDemo3 * * */ public class PathQuestionDemo1 extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. Create a Cookie Cookie cookie = new Cookie( "pathquestion" , "CookiePathQuestion" ); //2. Set the maximum lifetime of the cookie cookie.setMaxAge(Integer.MAX_VALUE); //3. Send the cookie to the client response.addCookie(cookie); //setHeader("Set-Cookie","cookie value") } public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } Copy code
/** * Get the cookie, the name is pathquestion */ public class PathQuestionDemo2 extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. Get all cookies Cookie[] cs = request.getCookies(); //2. Traverse the array of cookies for ( int i = 0 ;cs!= null && i<cs.length;i++){ if ( "pathquestion" .equals (cs[i].getName())){ //Found the cookie we wanted, and output the cookie value response.getWriter().write(cs[i].getValue()); return ; } } } public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } Copy code
/** * Get the cookie, the name is pathquestion */ public class PathQuestionDemo3 extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. Get all cookies Cookie[] cs = request.getCookies(); //2. Traverse the array of cookies for ( int i = 0 ;cs!= null && i<cs.length;i++){ if ( "pathquestion" .equals (cs[i].getName())){ //Found the cookie we wanted, and output the cookie value response.getWriter().write(cs[i].getValue()); return ; } } } public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } Copy code

Step 3: Configure Servlet

<!--Servlet for configuring cookie path problem cases--> < servlet > < servlet-name > PathQuestionDemo1 </servlet-name > < servlet-class > com.itheima.web.servlet.pathquestion.PathQuestionDemo1 </servlet-class > </servlet > < servlet-mapping > < servlet-name > PathQuestionDemo1 </servlet-name > < url-pattern >/servlet/PathQuestionDemo1 </url-pattern > </servlet-mapping > < servlet > < servlet-name > PathQuestionDemo2 </servlet-name > < servlet-class > com.itheima.web.servlet.pathquestion.PathQuestionDemo2 </servlet-class > </servlet > < servlet-mapping > < servlet-name > PathQuestionDemo2 </servlet-name > < url-pattern >/servlet/PathQuestionDemo2 </url-pattern > </servlet-mapping > < servlet > < servlet-name > PathQuestionDemo3 </servlet-name > < servlet-class > com.itheima.web.servlet.pathquestion.PathQuestionDemo3 </servlet-class > </servlet > < servlet-mapping > < servlet-name > PathQuestionDemo3 </the servlet-name > < URL-pattern >/PathQuestionDemo3 </URL-pattern > </the servlet-Mapping > copy the code

Step 4: Deploy the project

Just follow the project deployment in the first case.

4) Test results

By running the three Servlets of PathQuestionDemo1, 2 and 3 respectively, we found that the cookie written by demo1 can be retrieved in demo2, but it cannot be retrieved in demo3, as shown in the following figure:

5) Analysis and summary of path problems

Question: Who can get cookies for demo2 and demo3? The answer: demo2 can get to, demo3 fail to analyze:

1. we need to know how to determine a cookie? That is to use the three attribute combinations of cookies: domain+path+name , the domain of the same application is the same, in our case it is localhost.
And we take is with a cookie, so the name is the same, are pathquestion.
Well, not the same as the only path. But we have not set the path attribute of the cookie, which indicates that the path has a default value. Next, let's open this cookie to take a look and visit the PathQuestionDemo1 Servlet in the IE browser:

The content of the cookie: in this folder, you can try to find it.

We wrote the cookie through demo1, and the access path of demo1 is: http://localhost:9090/servlet/PathQuestionDemo1

By comparing two paths: request resource address and cookie path, it can be seen that the default value of cookie path is: request resource URI, without the resource part (in our case, there is no PathQuestionDemo1).

When does the client bring the cookie to the server, and when does it not? It is to look at the comparison of the request resource URI and the cookie path.

Request resource URI.startWith(cookie path) If it returns true, it will be taken, and if it returns false, it will not be taken.

To put it simply: to see whose address is more precise

For example:

Cookie path:/country/province/city

Request resource URI:/country/province without request resource URI:/country/province/city/county with

In our case:

Access URLURI partCookie PathWhether to carry cookiesCan I get cookies
PathQuestionDemo2/servlet/PathQuestionDemo2/servlet/bandCan get
PathQuestionDemo3/PathQuestionDemo3/servlet/WithoutCan't get

1.3 Server session tracking technology

Too much content, please move to another blog: yangyongli.blog.csdn.net/article/det...