The cookied/session of the servlet (i)

Source: Internet
Author: User
Tags set cookie

Lin Bingwen Evankaka original works. Reprint please specify the source Http://blog.csdn.net/evankaka
first, the concept of conversation

A session can be simply understood as: A user opens a browser, clicks multiple hyperlinks, accesses multiple Web resources on the server, and then closes the browser, the entire process is called a session.
Stateful session: A classmate came to the classroom, next time to come to the classroom, we will know that this classmate has come, this is called a stateful session.

Second, the conversation process to solve some problems?

Each user in the process of using the browser and the server session, will inevitably produce some data, the program to find a way to save the data for each user.

third, cookies Cookie Mechanism

In the program, session tracking is a very important thing. Theoretically, all request actions for one user should belong to the same session , and all request actions for another user should belong to another session, and they should not be confused. For example, any item that user a buys in a supermarket should be placed in A's shopping cart, regardless of when user a buys it, it belongs to the same session and cannot be placed in User B or User C's shopping cart, which is not part of the same session.

The Web application transmits data using the HTTP protocol. The HTTP protocol is a stateless protocol. Once the data has been exchanged, the client-to-server connection is closed, and exchanging the data again requires establishing a new connection. This means that the server is unable to track the session from the connection . that is, user a purchases a product into the shopping cart, and when the product is re-purchased, the server is unable to determine whether the purchase is a session of user A or User B. To track this session, you must introduce a mechanism. Cookies are such a mechanism. It can compensate for the lack of HTTP protocol stateless. Before the session, basically all websites use cookies to track conversations.

What is a cookie

Cookies mean "Cookie", which is a mechanism developed by the Netscape community, which is proposed by the group . Cookies are now standard and all major browsers such as IE, Netscape, Firefox, and opera support cookies. Because HTTP is a stateless protocol, the server does not know the identity of the client from the network connection. What do we do? give the client a pass, one per person, who must bring their own pass for whoever accesses it. This allows the server to confirm the identity of the client from the pass. That's how cookies work .

A cookie is actually a small piece of text information. The client requests the server and, if the server needs to log the user state, uses response to issue a cookie to the client browser. The client browser will save the cookie. When the browser requests the site again, the browser submits the requested URL along with the cookie to the server. The server checks the cookie to identify the user state. The server can also modify the contents of the cookie as needed.


Validity of Cookies

The maxage of a cookie determines the duration of the cookie, in seconds (Second). The Getmaxage () method and the setmaxage (int maxAge) method are used by the cookie to read and write the MaxAge property.

If the MaxAge property is positive, it means that the cookie will automatically expire after maxage seconds. The browser persists the cookie maxage as a positive number, which is written to the corresponding cookie file. The cookie remains in effect when the user logs on to the site, regardless of whether the client closes the browser or the computer, as long as it is maxage seconds. The cookie information in the following code will always be valid.


Cookie cookie = new Cookie ("username", "Helloweenvsfei"); New Cookie

Cookie.setmaxage (Integer.max_value); Set life cycle to Max_value

Response.addcookie (cookie); Output to Client


If MaxAge is negative, it means that the cookie is valid only in this browser window and in a subwindow that is open in this window, and the cookie is invalidated after the window is closed. MaxAge is a negative cookie, which is a temporary cookie that is not persisted and is not written to a cookie file. Cookie information is saved in the browser memory, so the cookie disappears when you close the browser. The default MaxAge value for cookies is –1.

If MaxAge is 0, the cookie is deleted. The cookie mechanism does not provide a way to delete cookies, so the effect of deleting cookies is realized by setting the cookie to expire immediately. Expired cookies are deleted by the browser from the cookie file or in memory.


For example:

Cookie cookie = new Cookie ("username", "Helloweenvsfei"); New Cookie

Cookie.setmaxage (0); Set life cycle to 0, cannot be negative

Response.addcookie (cookie); This sentence must be implemented


The response object provides a cookie action method with only one add action (cookie cookie).

To modify a cookie, you can only use a cookie of the same name to overwrite the original cookie for the purpose of the modification. You only need to change the maxage to 0 when you delete it.


Note: When you read a cookie from a client, other properties, including MaxAge, are unreadable and will not be committed. When a browser submits a cookie, it submits only the name and Value property. The MaxAge property is used only by the browser to determine whether the cookie expires.


Modification and deletion of cookies

Cookies do not provide modifications or deletions. If you want to modify a cookie, simply create a new cookie with the same name and add it to the response to overwrite the original cookie.

If you want to delete a cookie, simply create a new cookie with the same name and set MaxAge to 0 and add it to response to overwrite the original cookie. Note that it is 0, not a negative number. Negative numbers represent other meanings. The reader can verify with the program above and set different properties.


Note: When you modify or delete a cookie, all properties except value and MaxAge, such as name, path, domain, and so on, are identical to the original cookie. Otherwise, the browser will be treated as two different cookies without overwriting, causing the modification and deletion to fail.

Iv. Examples of use

Create a new Web project with the entire structure of the project as follows:


1.cookiedservlet.java

Package Com.mucfc;import Java.io.ioexception;import Java.io.printwriter;import java.util.date;import Javax.servlet.servletexception;import Javax.servlet.http.cookie;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;/** * cookied Test * @author Lin Bingwen Evankaka (blog: http://blog.csdn.net/evankaka) * @since 2015.6.24 */public class Cookiedservlet extends HttpServlet { public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {/        /Set the browser to UTF-8 encoding to receive, solve Chinese garbled problem Response.setcontenttype ("Text/html;charset=utf-8");        PrintWriter out = Response.getwriter ();        Gets the Cookie array passed when the browser accesses the access server cookie[] cookies = request.getcookies ();            If the user is a first-time access, then the resulting cookie will be null if (Cookies!=null) {out.write ("The time you last visited is:");                for (int i = 0; i < cookies.length; i++) {Cookie cookie = cookies[i]; if (COOkie.getname (). Equals ("LastAccessTime")) {Long LastAccessTime =long.parselong (Cookie.getvalue ());                    Date date = new Date (lastaccesstime);                Out.write (Date.tolocalestring ()); }}}else {Out.write ("This is your first time to visit this site!")        "); }//user reset the user's access time after access, stored in a cookie, and then sent to the client browser cookie cookie = new Cookie ("LastAccessTime", system.cu Rrenttimemillis () + "");//Create a Cookie,cookie name is LastAccessTime//Add the cookie object to the Response object, When the server outputs the contents of the response object, it also outputs the cookie to the client browser Response.addcookie (cookie);} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {DoG ET (request,response);}}

2. Web. XML Configuration

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xmlns:web= "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi: schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id= "Webapp_ ID "version=" 3.0 "> <display-name>ServletCookied</display-name> <servlet> <servlet-name> Cookiedservlet</servlet-name> <servlet-class>com.mucfc.CookiedServlet</servlet-class> </ servlet> <servlet-mapping> <servlet-name>CookiedServlet</servlet-name> <url-pattern>/ servlet/cookiedservlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file >index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>    Index.jsp</welcome-file> <welcome-file>default.html</welcome-file><welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </ Welcome-file-list></web-app>

3. Operation Result: Enter Http://lin-pc:8080/ServletCookied/servlet/CookiedServlet in Firefox browser

The first entry is the first access, and the next refresh shows the time of the last visit.


You can also see the cookied in the browser, the method is as follows, open the above URL unchanged


Here you can see the cookied:lastaccesstime of the record. The content is the value, here is encrypted, only the browser can read

The corresponding code is:

     After the user has visited, the user's access time is reset, stored in a cookie, and then sent to the client browser        Cookie cookie = new Cookie ("LastAccessTime", System.currenttimemillis () + "");//Create a Cookie,cookie name is LastAccessTime        //Add the cookie object to the Response object, When the server outputs the contents of the response object, it also outputs the cookie to the client browser        response.addcookie (cookie);

In the above example, the Setmaxage method is not used in the program code to set the validity period of the cookie, so when the browser is closed, the cookie is invalidated and if the cookie is still valid after the browser is closed, when the cookie is created, Set an expiration date for the cookie. As shown below:

   After the user has visited, the user's access time is reset, stored in a cookie, and then sent to the client browser        Cookie cookie = new Cookie ("LastAccessTime", System.currenttimemillis () + "");//Create a Cookie,cookie name is LastAccessTime        //Set cookie is valid for 1 days        Cookie.setmaxage (24*60*60);        The cookie object is added to the response object so that the server outputs the contents of the response object to the client browser        response.addcookie (cookie);

v. Note the details of cookies
    1. A cookie can only identify a single message that contains at least one name and set value (value) that identifies the information.
    2. A Web site can send multiple cookies to a Web browser, and a Web browser can store cookies provided by multiple Web sites.
    3. Browsers generally allow only 300 cookies, with a maximum of 20 cookies per site and a limit of 4KB per cookie size.
    4. If a cookie is created and sent to the browser, by default it is a session-level cookie (that is, stored in the browser's memory) that is 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 maximum aging to 0 is the command browser to delete the cookie.
Lin Bingwen Evankaka original works. Reprint please specify the source Http://blog.csdn.net/evankaka

The cookied/session of the servlet (i)

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.