A few practical examples--cookie read-write explanation

Source: Internet
Author: User

Cookie Introduction

The quotation of a cookie is intended to be "dim sum", which is the information that the server stores on the client's hard disk when the client accesses the Web server, as if it were a "dim sum" sent by the server to the customer. Servers can track customer status based on cookies, which is especially useful for situations where customers need to be differentiated (such as e-commerce).

When the client first requests access to the server, the server first stores a cookie containing information about the customer on the client, and each time the client requests access to the server, it contains the cookie in the HTTP request data, and the server resolves the cookie in the HTTP request. We can obtain relevant information about the customer.


The operating mechanism of a cookie is defined by the HTTP protocol, and most Web servers and browsers support cookies. Web server in order to support cookies, the following features are required:

• Add cookie data to the HTTP response results.

• Parse the cookie data in the HTTP request.

In order to support cookies, browsers need to have the following features:

• Parse the cookie data in the HTTP response results.

• Save the cookie data to the local hard drive.

• Read the cookie data on the local hard drive and add it to the HTTP request.

Cookie manipulation

There are three parts to the operation of cookies: reading, analyzing and writing.

Write a cookie

Cookie Thecookie = new Cookie ("username", "Tom");

Response.addcookie (Thecookie);

When the servlet writes a cookie to the client, the cookie's expiration date can also be set through the Setmaxage (Intexpiry) method of the Cookie class. The parameter expiry, in seconds, has the following meanings:

• If expiry is greater than 0, it instructs the browser to save the cookie on the client hard disk for Expriy seconds.

• If expiry equals zero, the browser is instructed to delete the current cookie.

• If expiry is less than 0, instruct the browser not to save cookies to the client hard drive. Cookies exist only in the current browser process, and when the browser process is closed, the cookie disappears.

The default validity period for cookies is-1. For Cookie,servlet from the client, the cookie's validity period can be read through the Getmaxage () method of the Cookie class.

Read Analytics Client Cookie

cookie[] cookies = request.getcookies ();

The GetCookies () method of the HttpServletRequest class returns an array of cookies that contain all the cookies in the HTTP request. If there are no cookies in the HTTP request, then the GetCookies () method returns NULL.

For each cookie object, call the GetName () method to get the name of the cookie and call the GetValue () method to get the value of the cookie.

Examples of use of cookies Example1
Read all cookies from the client, print out the name, value, and expiration date of each cookie, and then write a cookie to the client.

public class Cookieservlet extends HttpServlet {private static final long serialversionuid = 1L;    int count = 0;protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOE xception {this.dopost (request, response);} protected void DoPost (HttpServletRequest req, httpservletresponse Res) throws Servletexception, IOException { Res.setcontenttype ("Text/plain"); PrintWriter out = Res.getwriter (); cookie[] cookies = req.getcookies (), if (cookies! = null) {for (int i = 0; i < cookies.length; i++) {out.println ("Cookie N Ame: "+ cookies[i].getname ()); Out.println (" Cookie value: "+ cookies[i].getvalue ()); Out.println (" Cookie maxAge: "+ Cookies[i].getmaxage ());}} Else{out.println ("No cookie.");} Res.addcookie (New Cookie ("CookieName" + count, "Cookievalue" + count)); count++;}}

In the Web. xml file, map the URL for Cookieservlet to "/cookie" and follow the steps below to access Cookieservlet:

(1) Open the browser and visit Cookieservlet for the first time. Since there is no cookie at this time on the browser side, Cookieservlet returns "No cookie" to the client.

(2) Second access to Cookieservlet in the same browser. In step one, Cookieservlet has written a cookie to the client: "Cookiename0=cookievalue0", so this cookie is included in the HTTP request sent by the browser for the second time. Cookieservlet reads the cookie and returns the cookie information to the client, and the cookie displayed on the page is valid for-1, indicating that the cookie exists only in the current browser process and cannot be accessed by other browser processes.

(3) Visit Cookieservlet for the third time in the same browser. In step two, Cookieservlet has written a cookie to the browser: "Cookiename1=cookievalue1", Cookieservlet returns to the client information about the cookie generated in step one and step two.

(4) Open a new browser and access Cookieservlet from this browser for the first time. Because this browser client does not yet have any cookies at this time, Cookieservlet returns "No cookie" to the client.

(5) Access the servlet for the second time from a second browser. In step four, Cookieservlet writes a cookie to the client: "Cookiename3=cookievalue3", so Cookieservlet returns information about the cookie to the client.

Example2 modification and deletion of cookies

Read all of the client's cookies, look for a cookie named username, and then determine that if it does not exist, write a new cookie to the client: "Username=tom", which is valid for 1 hours, and if it exists and the value is Tom, change the value to Jack. If it exists and the value is jack, delete the cookie.

protected void DoPost (HttpServletRequest req, httpservletresponse Res) throws Servletexception, IOException {Cookie Cookie = Null;res.setcontenttype ("Text/plain"); PrintWriter out = Res.getwriter (); cookie[] cookies = req.getcookies (), if (cookies! = null) {for (int i = 0; i < cookies.length; i++) {out.println ("Cookie N Ame: "+ cookies[i].getname ()); Out.println (" Cookie value: "+ cookies[i].getvalue ()); if (Cookies[i].getname (). Equals (" Username ")) cookie = Cookies[i];}} Else{out.println ("No cookie.");} if (cookie==null) {cookie=new Cookie ("username", "Tom"); Cookie.setmaxage (60*60); Res.addcookie (cookie);} else if (Cookie.getvalue () equals ("Tom")) {Cookie.setvalue ("Jack"); Res.addcookie (cookie);} else if (Cookie.getvalue () equals ("Jack")) {cookie.setmaxage (0); Res.addcookie (cookie);}}

(1) Open the browser and visit Cookie1servlet for the first time. Since there is no cookie at this time on the browser side, Cookie1servlet returns "No cookie" to the client.

(2) Second access to Cookie1servlet in the same browser. In step one, Cookie1servlet has written a cookie to the browser: "Username=tom", the browser in this HTTP request contains this cookie,cookie1servlet to the client to return the cookie information:

Cookie Name:username

Cookie Value:tom

(3) Visit Cookie1servlet for the third time in the same browser. In step two, Cookie1servlet has changed the value of the cookie named "username" on the browser to "Jack", and the browser contains this cookie in the HTTP request. Cookie1servlet returns information about the modified cookie to the client:

Cookie Name:username

Cookie Value:jack

(4) Access Cookie1servlet in the same browser for the fourth time. In step three, Cookie1servlet has set the browser's name "username" cookie to "0", and the browser will remove the cookie when it processes the HTTP response results in step three. The browser does not contain any cookie information in this HTTP request, so Cookie1servlet returns "No cookie" to the client.

(5) Open a new browser and access the Cookie1servlet. In step four Cookie1servlet has written a cookie to the browser: "Username=tom", which is valid for 1 hours, so the browser will save it to the hard disk, other browsers can also ask this cookie. The newly opened browser contains the information that Cookie,cookie1servlet returns the cookie to the client in an HTTP request.

Assume there is a APP1 application and a APP2 application on Tomcat Server A, and there is a APP3 application on Tomcat Server B. Users access App1, APP2, app3 apps through a browser process.

Suppose a Web Component x in the App1 app saves a cookie on the browser, and when the browser requests access to other Web Components in App1, APP2, and app3 apps again, does the browser add the cookie to the HTTP request, So that these Web components can read the cookie?

By default, for security reasons, only Web Components in the App1 app can read the cookie. If you want to change the shared scope of a cookie, Web Component x in the App1 app can be written using SetPath (Stringpath) and Setdodomain (String domain) when writing cookies method to set the path and domain properties of the cookie.

(1) Share cookies with the App1 app and App2 app in the same Tomcat server A. The code for the write cookie for Web Component x in the App1 app:

Cookie cookie = new Cookie ("username", "Tom");

Cookie.setpath ("/");

Res.addcookie (cookie);

The parameter for Serpath () above is "/", which indicates the root path of the Tomcat server, so all Web apps in the same Tomcat server can share the cookie.

(2) only the APP2 app in Tomcat Server A will be allowed access to the cookie. The code for the write cookie for Web Component x in the App1 app is as follows;

Cookie cookie = new Cookie ("username", "Tom");

Cookie.setpath ("/app2/");

Res.addcookie (cookie);

The parameter for SetPath () above is "/app2/", so only the App2 app in Tomcat Server A can access the Cookie,app1 app and cannot access the cookie.

(3) Only Web Components that are located under the "/sub" subpath in the App1 app in Tomcat Server a access the cookie. Write cookie code for Web Component x in the app in App1:

Cookie cookie = new Cookie ("username", "Tom");

Cookie.setpath ("/app1/sub");

Res.addcookie (cookie);

(4) Let all Web Apps in Tomcat Server B access the cookie, assuming that the domain name of Tomcat Server B is www.cat.com. The code for the write cookie for Web Component x in the App1 app:

Cookie cookie = new Cookie ("username", "Tom");

Cookie.setdomain (". cat.com");

Res.addcookie (cookie);

advertising promotion of simulated Taobao and other websites

A similar website will store browsing history data on the client when the customer browses the information, and promote the most recently viewed product information to the customer the next time the customer opens the website.

Each connection on the page represents a category of items, and the cookie is saved to the client via Addcookieservlet when the connection is clicked: "itemsnum:6923384801114":
public class Addcookieservlet extends HttpServlet {private static final long serialversionuid = 1L; protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { This.dopost (request, response);} protected void DoPost (HttpServletRequest req, httpservletresponse Res) throws Servletexception, IOException {Cookie Cookie = Null;res.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out = Res.getwriter (); Out.println ("

Open the browser to access Http://localhost:8080/webdemo/addCookie. The initial page is:

Click on one of the connections, then open another browser or close the current page and then open the connection above, the Discovery page will show the last product number viewed:


This kind of application can be based on the user's use, dynamically set up promotional information, customer personalized preferences, but also in the logic to increase the judgment, to see how long the customer separated to visit the site.

use cookies to simulate automatic login

Users log in once and select Automatic login, the next time you log in to the site without the login step, you can go directly to the Web page.

First, there should be a filter to determine whether the user set up automatic login, if set up automatic login to read the data from the cookie directly log in, access to the site. Create a filter and register it in the app:

public class Loginfilter implements Filter {public void init (Filterconfig fconfig) throws servletexception {}public void D Estroy () {}public void DoFilter (ServletRequest reqest, Servletresponse response,filterchain chain) throws IOException, servletexception {HttpServletRequest req = (httpservletrequest) reqest; HttpServletResponse res = (httpservletresponse) response;if (!req.getrequesturi (). EndsWith ("login.html") &&! Req.getrequesturi (). EndsWith ("Loginservlet")) {HttpSession session = Req.getsession (); User Sessionuser = (user) Session.getattribute ("user"), if (Sessionuser = = null) {cookie[] cookies = req.getcookies (); if (c Ookies! = null) {for (int i = 0; i < cookies.length; i++) {if (Cookies[i].getname (). Equals ("Login")) {String Logininfo = Cookies[i].getvalue (); string[] Infos = Logininfo.split ("&", 2); String username = infos[0]; String password = infos[1]; User user = new user (username, password), Session.setattribute ("user", user), Chain.dofilter (req, res); return;}} Res.sendrEdirect ("login.html"); return;}} Chain.dofilter (reqest, Response);}}

In this filter first take the user value from the session, if not determine whether the client is named as login cookie, if there is a sign that the user has set up automatic login, and has saved the login information (that is, already logged in) will jump directly to the target page, if none of the above conditions are met, Then jump to the login page. The configuration code for the filter in the Web. xml file is:

<filter>  <filter-name>LoginFilter</filter-name>  <display-name>loginfilter</ Display-name>  <filter-class>filter. loginfilter</filter-class>  </filter>  <filter-mapping>  <filter-name> loginfilter</filter-name>  <url-pattern>*</url-pattern>  </filter-mapping>

Then create the login page:

<! DOCTYPE html>
The login page requests the servlet to perform the validation of the data in the servlet, among other things:
public class Loginservlet extends HttpServlet {private static final long serialversionuid = 1l;protected void Doget (httpse Rvletrequest request, HttpServletResponse response) throws Servletexception, IOException {this.dopost (Request, Response);} protected void DoPost (HttpServletRequest req, httpservletresponse Res) throws Servletexception, IOException {Boolean Auto = Req.getparameter ("Autologin")!=null&&req.getparameter ("Autologin"). Equals ("on")? True:false; String username = req.getparameter ("username"); String Password = req.getparameter ("password"); User user = new user (username, password); HttpSession session = Req.getsession (); Session.setattribute ("User", user); Cookie cookie = null; cookie[] cookies = req.getcookies (), if (cookies!=null) {for (int i = 0; i < cookies.length; i++) {if (Cookies[i].getname ( ). Equals ("Login")) {cookie = Cookies[i];cookie.setvalue (username + "&" + password);}}} if (cookie = = null) {cookie = new Cookie ("Login", username + "&" + password);} if (auto) {COokie.setmaxage (60*60*24*7);} Else{cookie.setmaxage (0);} Res.addcookie (cookie); Res.sendredirect ("hello.jsp");}}
The work done in this servlet is to save the user information to the session and manipulate the cookie according to the logical judgment. After successful login page go to welcome page hello.jsp:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "    pageencoding=" Utf-8 "import=" Helloworld.bean.User "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

A simple javabean:user is used when saving user information.

These are the pages used in the experiment. Follow these steps to access:

(1) After starting the project, open the browser to access any page in the project. such as: http://localhost:8080/webdemo/hello.jsp, the discovery will be intercepted to the login page, enter the login information, at this time do not tick automatic login, click Login, the page jumps to hello.jsp.

(2) Close the browser and then open and access http://localhost:8080/webdemo/hello.jsp, to be intercepted to the login page. After filling in the login information, tick automatic login, and close the browser after successful login.

(3) Open the same browser and continue to access http://localhost:8080/webdemo/ HELLO.JSP, the discovery is not intercepted at this time, because the previous step to the client to write a cookie, open the browser and access, the program read the user information directly into the session, completed the automatic login function.

Access http://localhost:8080/webdemo/login.html. At this time do not check the automatic login, after successful login, repeat step one or two, the automatic login function has been canceled.

A few practical examples--cookie read-write explanation

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.