In-depth discussion of session implementation principles

1.Session implementation mechanism
server is how to achieve a user's browser session as a service?

Schematic diagram of Session principle

Explanation:
If browser A first accesses Servlet1, at this time it creates a Session with an ID number of 110, and then Servlet1 returns this ID number to browser A in the form of a cookie. Then, if browser A continues to access Servlet2, then This request will bring the Cookie value: JSESSIONID = 110, and then the server finds the Session in memory according to the ID number passed by Browser A.
At this time, if browser B came to access Servlet1, its request did not bring the cookie value of JSESSIONID, because it also uses Session, so the server will create a new Session, ID number is 119, and this ID number is Cookie Way back to browser B. The subsequent process is the same as A.

We illustrate this principle through Servlet1 and Servlet2 in [Basic Knowledge of Session (1)], where Servlet1 is used to create a Session and add attributes; Servlet2 is used to read the attributes in the Session.
Now we visit Servlet1 and capture the package:

Set-Cookie

As you can see, there is no cookie information in Request Headers, and there is such a sentence in Response Headers:

Set-Cookie: JSESSIONID=2150AE444BF83FDACEA04BD0289F5AE2; Path=/Session1/; HttpOnly

This shows that the server passed the JSESSIONID attribute to the client through the cookie.

Then we visit Servlet2 and capture the package as follows:

Cookie

You can see that the Set-Cookie header does not appear in the Response Headers, and the Cookie header is included in the Request Headers:

Cookie: JSESSIONID=2150AE444BF83FDACEA04BD0289F5AE2

And this header contains JSESSIONID, and its value is the value of JSESSIONID in our previous Set-Cookie.
This proves the principle of the Session we illustrated earlier, that is, the mechanism by which the server can distinguish different sessions for different browsers.

But there is another problem here: We said before that cookies are shared by multiple browsers. Since JSESSIONID is saved on the client as a cookie, why can't it be shared by multiple browsers?

In fact, the answer is very simple. This cookie for storing JSESSIONID is a Session Cookie, not a Persistent cookie. When learning cookies, we learned how to set the cookie life cycle. If the cookie life cycle is set, the cookie will be written to the disk file and stored until its end of the life cycle, and then automatically cleared; and If the life cycle of the cookie is not set, then this cookie is the Session Cookie, that is, the session cookie, which only exists during the period when the browser is opened. If the browser is closed, the cookie will disappear.
In other words, the Session Cookie exists in the browser's memory, and it disappears when the browser is closed. Therefore, the JSESSIONID also exists in the Session Cookie, so naturally, it cannot be shared by multiple browsers!

So is it possible to close a browser and then open the browser to access the page just now, and this page can still save your information? For example, after closing IE and then opening IE, the last purchased product is still there.

Analysis, if we do not set the Session life cycle in the program, so its life cycle is the default time of 30min, then if the browser is closed, according to the Session implementation mechanism introduced earlier, the server does not know whether the browser has been closed at this time Yes, that is to say, the session on the server side still exists, and will not be destroyed until 30 minutes later.
So if we bring cookies at this time: JSESSIONID = 2150AE444BF83FDACEA04BD0289F5AE2, go to the page just before the browser is closed, the server can still find the previous Session, and provide us with relevant data.

Through the above analysis, this function can be achieved using the combination of Session and Cookie.

Now, let's modify Servlet1 and Servlet2.
Set the Session in Servlet1, add attributes, and then pass the ID of the Session back to the client through the cookie, and the name of the cookie is "JSESSIONID", the value is the ID of the Session, this ID can be directly passed through the session getId () gets. , Its doGet method is as follows:

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();

    //创建一个session,默认生命周期为30min,并放入一个属性
    HttpSession session = request.getSession();
    session.setAttribute("name", "小明");
    out.println("创建Session成功,并放入了一个值");

    // 把该sessionid保存在cookie
    // 这个cookie的键为JSESSIONID
    Cookie cookie = new Cookie("JSESSIONID", session.getId());
    cookie.setMaxAge(3600);
    response.addCookie(cookie);
}

Servlet2 remains unchanged, it still just goes to the session to get this attribute. Experiments show that after closing the browser, open the browser again to access Servlet2, and the value in the session can still be retrieved.

test

Why? Because our Servlet1 has saved the JSESSIONID in the disk file by cookie. Understand the realization mechanism of Session, this is not difficult to understand.

2. After the user to disable Cookie Session process
where there is a situation, if the user's browser to disable the Cookie how to do? For example, I disabled Chrome cookies as follows:

Disable cookies

At this time, when we go to visit some large websites, such as shopping websites, we can obviously find that many functions of the website can no longer be realized normally. For example, if I log in to JD, the server cannot obtain the verification code I entered, as shown in the following figure:

JD tips

The reason is very simple, because I disabled cookies, so the same, the server-side session can not be used, because cookies can not save JSESSIONID.

Speaking back to the last simple shopping cart example in [Servlet (2) Simple Application], if we disable cookies, we will find that there is only one book that has just been purchased in the shopping cart every time, and we ca n’t find the previous one The reason is the same, so how to solve this situation?

Solution: URL rewriting

The response in the Servlet provides a method for URL rewriting:

response.encodeRedirectURL (String url)-used to rewrite the url address after the sendRedirect method response.encodeURL (String url)-used to rewrite the url address
of the form action and hyperlink

So what does url rewriting mean? In fact, the JSESSIONID is artificially appended to the url. For example, if we modify the simple shopping cart we wrote before, all click-to-purchase hyperlinks in ShowBook ​​must be rewritten.
We wrote this before:

out.println("<tr><td>"+book.getName()+"</td><td><a href='/MyCart/BuyBookCl?id="+book.getId()+"'>点击购买</a></td></tr>");

Now for URL rewriting:

request.getSession();
String url = "/MyCart/BuyBookCl?id="+book.getId();
url = response.encodeURL(url);
out.println("<tr><td>"+book.getName()+"</td><td><a href='"+url+"'>点击购买</a></td></tr>");

It should be noted that the request.getSession () method must be called or ensured before rewriting.

We can see the difference between these links through the source code file. Before rewriting, the source code to access ShowBook ​​looks like this:

ShowBook ​​source code before URL rewriting

After rewriting:

ShowBook ​​source code after URL rewriting

It can be seen that after the URL is rewritten, the jsessionid parameter is automatically appended to the url, thereby ensuring that our Session continues to be used normally when cookies are disabled. At this time, we check the address bar of the shopping cart as follows, you can clearly see the jsessionid parameter:

ShowMyCart
transfer from

Published 17 original articles · won 24 · views 280,000 +

Guess you like

Origin blog.csdn.net/qq_22956867/article/details/79415953