[Original]java Web Learning Note 28: Session and State management cookie mechanism

Source: Internet
Author: User
Tags session id send cookies

1. Session and state Management

1) Background

HTTP protocol is a stateless protocol , the Web server itself does not recognize which requests are issued by the same browser, each request of the browser is completely isolated;

As a Web server, ② must be able to use a mechanism to uniquely identify a user while recording the user's state;

③ question: How to realize the shopping cart in the online store: When a user logs in from the login page of the website and then enters the shopping page, the server program responsible for processing the purchase request must know the user information from the program that processed the last request.

2) sessions and session state

①web sessions in an app: a sequence of requests and responses that occur continuously between a client browser and a Web server;

②web session state: Refers to the state information generated by the Web server and the browser during the session, and with the use of Session state, the Web server can associate a series of request and response processes belonging to the same session ;

3) How to implement a stateful session

①web server-side program to be able to distinguish from a large number of request messages which request messages belong to the same session, that is to be able to identify the access request from the same browser, which

Requires the browser to identify every request message it makes: the request message that belongs to the same session comes with the same identification number, and the request message belonging to a different session always comes with a different identification number, which is called the session ID (SessionID);

② in the Servlet specification, the following two mechanisms are used to complete session tracking: Cookie session;

2.Cookie mechanism

1) The cookie mechanism uses a scheme that maintains HTTP status information on the client;

2) A cookie is a small text file that is transmitted to the browser by the Web server in the HTTP Response message header when the browser accesses a resource of the Web server;

3) Once a cookie is saved by the Web browser, it will be passed back to the Web server in the HTTP request header each time it accesses the Web server;

4) Bottom-up principle: The Web server sends cookie information to the browser by adding the Set-cookie response header field in the HTTP response message, and the browser adds a cookie request header to the HTTP request message field to pass the cookie back to the Web server;

5) A cookie can only identify a single message that contains at least one name and set value (value) that identifies the information;

6) A Web site can send multiple cookies to a Web browser, and a Web browser can store cookies provided by multiple Web sites;

7) Browsers generally only allow 300 cookies, each site holds a maximum of 20 cookies, each cookie size limit of 4KB;

3. APIs for cookies in a Servlet

1) A Javax.servlet.http.Cookie class is provided in the Servlet API to encapsulate cookie information, which contains methods for generating cookie information and extracting individual attributes of cookie information

2) Methods of the Cookie class

① Constructor Method: Public Cookie (String name,string value)

②getname method

③setvalue and GetValue method

④setmaxage and Getmaxage method

⑤setpath and GetPath method

3) A Addcookie method is defined in the HttpServletResponse interface that is used to add a Set-cookie response header field to the HTTP response message sent to the browser

4) A GetCookies method is defined in the HttpServletRequest interface that is used to read all cookie entries from the cookie Request header field of the HTTP request message

4.Cookie of transmission

1) Create Cookie Object

2) Set Maximum aging

3) Put the cookie into the HTTP response header

Attention:

① If a cookie is created and sent to the browser. By default it is a session-level cookie;

stored in the browser's memory and deleted after the user exits the browser. If you want the browser to store the cookie on disk, you need to use maxage and give a time in seconds . Setting the maximum limitation to 0 is the command browser to delete the cookie;

② sending a cookie requires the use of the HttpServletResponse Addcookie method to insert the cookie into a Set-cookie HTTP response header. Since this method does not modify any of the previously specified Set-cookie headers, it creates a new header, so this method is called Addcookie, not Setcookie.

5. Reading of cookies

① calls Request.getcookies. To get the cookie sent by the browser, call HttpServletRequest's GetCookies method, which returns an array of cookie objects corresponding to the value entered by the cookie header in the HTTP request;

② loops the array, invoking the GetName method of each cookie until the cookie of interest is found;

Instance code:

 cookie.jsp

1<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "2pageencoding= "UTF-8" session= "false"%>3<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >456<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">7<title>cookie Test </title>89<body>Ten  One<% A         //using cookie classes to represent cookies in the Java Web Specification -         //Read Cookies -         //1. Obtaining Cookies thecookie[] Cookies =request.getcookies (); -         if(Cookies! =NULL&& cookies.length > 0 ){ -              for(Cookie cookie:cookies) { -                 //2. Get the name and value of the cookie +Out.print (Cookie.getname () + ":" +Cookie.getvalue ()); -Out.print ("<br>"); +             } A}Else{ at             //Send Cookies -Out.print ("No cookies are being created and returned"); -              -         //1. Create a Cookie object -Cookie cookie =NewCookie ("name", "Jason"); -          in         //setmaxage: Sets the maximum age of the cookie, in seconds, if 0, indicates that the cookie is immediately deleted and, if negative, indicates that the cookie is not stored and, if positive, indicates how long the cookie is stored -Cookie.setmaxage (30); to          +         //2. Call response a method to wear cookies to the client - Response.addcookie (cookie);  the          *          $         }Panax Notoginseng%> -  the</body> +

6. The difference between a session cookie and a persistent cookie

① If the expiration time is not set, the cookie disappears when the browser window is closed, as long as the cookie's lifetime is the browser session. This cookie, which is the lifetime of the browser session, is referred to as a session cookie. Session cookies are generally not saved on the hard disk but in memory;

② If the expiration time is set, the browser will save the cookie to the hard disk, turn it off again and open the browser again, these cookies remain valid until the set expiration time is exceeded;

③ cookies stored on the hard disk can be shared among different browser processes, such as two IE windows. And for the memory stored in the cookie, different browsers have different ways of processing;

7. Summary

1) Understand the content of cookies

2) Mastering the API

[Original]java Web Learning Note 28: Session and State management cookie mechanism

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.