Java Web (3) Session Mechanism, Cookie and Session Detailed Explanation

1. Session mechanism

    A technique commonly used in web programs to track a user's entire session . Commonly used session tracking technologies are cookies and sessions. Cookie determines user identity by recording information on the client side , and Session determines user identity by recording information on the server side .

    A session refers to: it is like making a phone call, A calls B, after connecting, the session starts, and the session ends until the call is hung up, and the browser accesses the server, just like making a phone call, the browser A sends a request to the server and accesses the web program, and the session is already connected. No matter how many requests the browser sends (just like talking after connecting the phone), it is regarded as a session until the browser is closed. Session ends. Note that a browser is equivalent to a phone. If you use the Firefox browser to access the server, it is a session, and then open the Google browser to access the server. This is another session, although it is on the same computer. One user is accessing, however, this is two different sessions.

    After knowing what a session is, think about a problem. A browser can establish a session by accessing a server. If other computers access the server at the same time, many sessions will be created. Take some shopping websites as an example, we visit The server of a shopping website, the session is created, and then click to browse the products, add the interested products to the shopping cart first, and wait for the payment together. This seems to be a very common operation, but think about it, if there are many different The browser on the computer is also accessing the server of the shopping website at the same time. How about doing a similar operation with us? How does the server remember the user, and how does it know that any product purchased by user A should be placed in A's shopping cart, and no matter when user A purchased it, it cannot be placed in user B or user C's shopping cart? So there are two technologies, cookie and session. As said in the first line, cookie and session are used to track the entire session of the user.

     Differences and connections between cookies and sessions

      If a coffee shop offers a free one for 5 cups of coffee, but the chance of consuming 5 cups of coffee at one time is very small, then there needs to be some way to record the consumption of a certain customer. Just imagine the following scenarios:

      1. The store clerk is very powerful and can remember the consumption amount of each customer. As soon as the customer walks into the coffee shop, the clerk will know how to treat it. This practice is that the protocol itself supports state. But the http protocol itself is stateless

      2. A card is issued to the customer, which records the quantity of consumption and generally has an expiration date. Every time a customer makes a purchase, if the customer presents the card, the purchase is linked to a previous or future purchase. This practice is to maintain state on the client side. Also known as cookies. Customers are equivalent to browsers. How cookies work is explained in detail below.

      3. Issue a membership card to the customer, and no information is recorded except the card number. Every time the customer makes a purchase, if the customer presents the card, the clerk will find the record corresponding to the card number in the store's record book and add some consumption information. . This practice is to maintain state on the server side.

      Since the HTTP protocol is stateless, and it is not desirable to make it stateful due to various considerations, the latter two solutions have become a realistic choice. Specifically, the cookie mechanism adopts the scheme of maintaining state on the client side, while the session mechanism adopts the scheme of maintaining state on the server side. At the same time, we also see that because the server-side state-keeping scheme also needs to save an identifier on the client side, the session mechanism may need to rely on the cookie mechanism to achieve the purpose of saving the identifier, but in fact it has other options.

 

二、Cookie

     The reasons for using cookies have been introduced above, as well as some features of cookies, such as being stored on the client side and used to record user identity information. Now let's take a look at how to use cookies.

     Taking the example of the membership card above, the second solution is adopted, and the problems that need to be solved are: how to distribute the membership card, the content of the membership card, how the customer uses the membership card, the validity date of the membership card, the membership card scope of use

     1. How to distribute the membership card and the content of the membership card: that is, how is the cookie created? How to send to client after creation?

        Created by the server, it is equivalent to creating a membership card in a coffee shop. When creating a membership card, the content in the membership card will also be set.

          Cookie cookie = new Cookie(key,value); //Store content in key-value pairs,

          response.addCookie(cookie); //Send back to the browser

        Note: Once the cookie is created, you cannot add other key-value pairs to it, but you can modify its content.

          cookie.setValue(); //Modify the value corresponding to the key

     2. How does the customer use the membership card, how does the cookie work on the client side, and what is the working principle?

        

        This process is equivalent to that the coffee shop has created a membership card, and has set up the contents and handed it to the customer. The next time the customer comes over, he will bring the membership card and know that you are a member, and then the coffee shop will Just get your membership card and operate it.

     3. What is the validity date of the membership card? That is, cookies also have an expiration date.

        This can be set freely, the default is to close the browser, the cookie is useless.

        cookie.setMaxAge(expiry); //Set the time the cookie is saved by the browser.

          expiry: unit in seconds, the default is -1,

             expiry=-1: It means that after the browser is closed, that is, after the session ends, the cookie will be invalid, and there will be no more.

             expiry>0: After the browser is closed, the cookie will not expire and still exists. And the cookie will be saved to the hard disk, and will not be automatically deleted by the browser until the set time expires.

             expiry=0: delete cookies. Regardless of the previous expiry=-1 or expiry>0, when expiry=0 is set, the cookie will be deleted by the browser.

    

    4. What is the scope of the membership card? For example, Starbucks has a branch in Beijing and a branch in Shanghai. We only apply for a membership card at Starbucks in Beijing, so when we go to Shanghai, we cannot use the membership card for discounts. The same is true for cookies. You can set the access path for the server to obtain the cookie, but not all servlets in the web project on the server can access the cookie.

      Cookie default path: the currently accessed servlet parent path.

        例如:http://localhost:8080/test01/a/b/c/SendCookieServlet

          Default path: /test01/a/b/c In other words, all servlets under this default path can get cookies, and MyServlet /test01/a/b/c/MyServlet can get cookies.

      Modify the access path of the cookie

        setPath("/"); //Under this server, any item and any location can get the cookie,

          Passage: Ensure that all web projects under tomcat can share the same cookie 

                 For example: tieba , wenku , beike multiple projects share data. For example username.

        setPath("/test01/"); //The cookie can be obtained anywhere under the test01 project.

 

    5. Summary Cookies:

        work process:

          1. The servlet creates a cookie, saves a small amount of data, and sends it to the browser.

              2. The browser obtains the cookie data sent by the server and automatically saves it to the browser.

                3. The browser will automatically send the cookie data to the server the next time you visit.

        cookie manipulation

          1.创建cookie:new Cookie(name,value)

              2. Send a cookie to the browser: HttpServletResponse.addCookie(Cookie)

          3. The servlet receives cookies: HttpServletRequest.getCookies() All cookies sent by the browser

         cookie features

              1. The size of each cookie file: 4kb, if it exceeds 4kb, the browser does not recognize it

              2. A web site (web project): send 20

                3. One browser saves the total size: 300

                4. Cookies are not secure and may reveal user information. Browsers support disabling cookies.

              5. Default life cycle: Like the browser session, the cookie is destroyed when the browser is closed. --- Temporary cookies

        cookie api

          getName() gets the name, the key in the cookie

          getValue() gets the value, the value in the cookie

          setValue(java.lang.String newValue) Set the content to modify the value corresponding to the key.

          setMaxAge(int expiry) Set the valid time []

          setPath(java.lang.String uri) set the path []  

          setDomain(java.lang.String pattern) Set the domain name, generally invalid, it is automatically set by the browser, setDomain(".itheima.com")

             www.itheima.com / bbs.itheima.com can be accessed

             abitheima.com cannot be accessed

             Function: Set the scope of the cookie. The domain name + path together constitute the scope of the cookie. The setPath set separately above is useful because the browser automatically sets the domain name attribute, but we must know that there is such an attribute to set the domain name of

          Whether isHttpOnly() is only used by the http protocol. It can only be obtained by servlet through getCookies(), not by javascript.

          setComment(java.lang.String purpose) (understand) //The information describing the cookie (description function), which can be seen when the browser displays the cookie information

          setSecure(boolean flag) (know) Whether to use secure transport protocol. When it is true, the cookie will be sent to the server only when the connection is requested by https, but not when the connection is made by http, but the server can still send it to the browser.

          setVersion(int v) (understand) The argument is either 0 (compiled by the legacy Netscape cookie specification) or 1 (compiled by the RFC 2109 specification). This is useless, I don't understand

        Note: Cookies cannot be sent in Chinese. If you want to send Chinese, special processing is required.

          JDK provides tools for coding

            URLEncoder: encoding

            URLDecoder: decode

            //send cookies

            Cookie cookie = new Cookie(URLEncoder.encode("哈哈"),URLEncoder.encode("呵呵"));

            response.addCookie(cookie);

            //Get the Chinese content of the cookie

            URLDecoder.decoder(request.getCookie().getName);  //获取key

            URLDecoder.decoder(request.getCookie().getValue);  //获取value  

     6. cookie case

         6.1. Remember your username

            When logging in, the user name is obtained on the server side, then a cookie is created, the user name is stored in the cookie, and sent back to the browser. Take out the information and see if the user name is saved. If it is saved, use it directly. If not, write the user name by yourself.

         6.2. History

            For example, shopping websites will have our browsing records. The implementation principle is actually using cookie technology. Every time a product is browsed, it is stored in the cookie. When the browsing record needs to be displayed, it is only necessary to take out the cookie and traverse it.  

 

3. Session

     Similarly, the third method of the membership card example is to issue a membership card to the customer, and no information is recorded except the card number. Every time the customer makes a purchase, if the customer presents the card, the clerk will record it in the store's record book. Find the record corresponding to this card number and add some consumption information. This practice is to maintain state on the server side. This is the usage of session, to maintain state on the server side and save some user information.

     Function: The server is used to share data technology,

            

     Session principle analysis:

        First, when the browser requests the server to access the web site, when the program needs to create a session for the client's request, the server will first check whether the client request already contains a session identifier, called SESSIONID. If it already contains a sessionid, it means If a session has been created for this client before, the server retrieves the session according to the sessionid and uses it. If the client request does not contain the session id, the server creates a session for the client and generates a session id associated with this session. , the value of sessionid should be a string that is neither repeated nor easy to find patterns to imitate. This sessionid will be returned to the client to save in this response. The way to save this sessionid can be a cookie. During the interaction process, the browser can automatically send the identifier back to the server according to the rules, and the server can find the corresponding session according to the sessionid, and return to the beginning of this text.

     Get session:

        request.getSession(); //If not, a new one will be created, equivalent to getSession(true);

          Some people don't understand why the session is obtained through the request. It can be understood in this way. When obtaining the session, it is necessary to detect whether there is a session identifier in the request, so it is necessary to use the request to obtain the session.

        request.getSession(boolean); //true: no will be created, false: no will return null

 

     session attribute operation:

        xxxAttribute(...)

          Used to store some information before it can be shared 

          setAttrubute(key,value);

          getAttribute(key);

     

     session life cycle

        Often hear such a misunderstanding "as long as you close the browser, the session is gone". In fact, you can imagine the example of a membership card. Unless the customer takes the initiative to cancel the card, the store will never delete the customer's information easily. The same is true for sessions. Unless the program notifies the server to delete a session, the server will keep it. The program generally sends an instruction to delete the session when the user logs off. However, the browser never actively informs the server that it will be closed before closing, so the server has no chance to know that the browser has been closed. The reason for this illusion is that most session mechanisms use session cookies to save session id. , and the session id disappears after closing the browser, and the original session cannot be found when connecting to the server again. If the cookie set by the server is saved to the hard disk, or some method is used to rewrite the HTTP request header sent by the browser, and the original session id is sent to the server, the original session can still be found by opening the browser again. 

        It is precisely because closing the browser will not cause the session to be deleted, forcing the server to set an expiration time for the session, usually 30 minutes. When the time since the client last used the session exceeds this expiration time, the server can consider the client After the activity has been stopped, the session will be deleted to save storage space

        We can also control the effective time of the session ourselves

          session.invalidate() destroys the session object

          setMaxInactiveInterval(int interval) Set the effective time in seconds

          Configure the effective time of the session in web.xml

            <session-config>

              <session-timeout>30</session-timeout> Unit: minutes

            <session-config>

    

        So, after discussing this, the life cycle of a session is:

            Creation: first call to getSession()

            destroy:

               1. Timeout, default 30 minutes

               2. Execute api: session.invalidate() to destroy the session object, setMaxInactiveInterval(int interval) to set the valid time, in seconds

               3. The server is shut down abnormally

                  Suicide, close the JVM immediately

                  If it is closed normally, the session will be persisted (written to the file, because the default timeout period of the session is 30 minutes, after the normal shutdown, the session will be persisted, and it will be deleted after 30 minutes)

                  位置: D:\java\tomcat\apache-tomcat-7.0.53\work\Catalina\localhost\test01\SESSIONS.ser

 

     URL rewriting for session id

         When cookies are disabled in the browser, cookie-based sessions will not work properly, and a new session will be created each time request.getSession() is used. It can't achieve the purpose of session sharing data, but we know the principle, just pass the session id to the server session to work normally.

        Solution: Pass the session id to the server via URL: URL rewriting

          Manual way: url;jsessionid=....

          api method:

               encodeURL(java.lang.String url) does all URL rewriting

               encodeRedirectURL(java.lang.String url) for redirection URL rewriting 

               These two usages are basically the same, but considering special circumstances, the link to be accessed may be redirected to other servlets for processing, so the session id information you bring with the above method cannot be transmitted to other servlets at the same time. At this time Just use the encodeRedirectURL() method 

          If the browser disables cooke, the api will automatically append the session id, if not, the api will not make any modifications.

          Note: If the browser disables cookies, all urls for web projects will need to be rewritten. Otherwise the session will not work properly

        When cookies are disabled,

                

 

4. Summary

    Know what is a cookie and what is a session?

       Cookie is a technology that records user information on the client side, because the http protocol is stateless, and cookies are generated to solve this problem. Some applications such as recording usernames

       Session is a technology for recording user information on the server side. Generally, session is used to share data on the server side.

    How do cookies work? How does session work?

       The working principle of cookie, you can see the picture above explaining the cookie. The cookie is created by the server and sent back to the browser, and every time the server is requested, the cookie will be taken over, so that the server knows which user the user is. The cookie uses key-value pairs to store information, and a cookie can only store one key-value pair. So when you get a cookie, you will get all the cookies, and then traverse from them.

             

       The working principle of the session is to rely on the cookie for support. The session is created when request.getSession() is used for the first time, and a unique sessionid will be created for the session and stored in the cookie, and then sent to the browser and the browser. Every time a request is made, this sessionid will be carried, and the server will recognize the sessionid, and if it knows the sessionid, it can find which session. In order to achieve the purpose of sharing data. It should be noted here that the session will not die when the browser is closed, but will wait for the timeout period.

  

      If you still don't understand the cookie and session, everyone will use it. You just need to understand why you need to use the cookie and session. You can look at the example of the membership card. The cookie and session are only to solve the stateless problem of the http protocol. This defect, in order to record user information, records the state between the browser and the server and is derived.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325816619&siteId=291194637