In-depth analysis and research on cookies

Source: Internet
Author: User


First, cookies are text files stored on the client, which store a large amount of user information.

From the source code of the cookie, we can see that it implements the cloneable interface,

The following is the cookie construction method. It can be seen that it is stored as a key-value pair.

 public Cookie(String name, String value) {if (!isToken(name)|| name.equalsIgnoreCase("Comment")// rfc2019|| name.equalsIgnoreCase("Discard")// 2019++|| name.equalsIgnoreCase("Domain")|| name.equalsIgnoreCase("Expires")// (old cookies)|| name.equalsIgnoreCase("Max-Age")// rfc2019|| name.equalsIgnoreCase("Path")|| name.equalsIgnoreCase("Secure")|| name.equalsIgnoreCase("Version")|| name.startsWith("$")    ) {    String errMsg = lStrings.getString("err.cookie_name_is_token");    Object[] errArgs = new Object[1];    errArgs[0] = name;    errMsg = MessageFormat.format(errMsg, errArgs);    throw new IllegalArgumentException(errMsg);}this.name = name;this.value = value;    }
It can be seen that there is an istoken () method. What is the role of this method? From the source code, we can see that this method is used to compare and determine whether the name here is a reserved keyword, if yes, false is returned, and an exception is thrown in the cookie constructor. If no reserved keyword is returned, this constructor is called.
private boolean isToken(String value) {int len = value.length();for (int i = 0; i < len; i++) {    char c = value.charAt(i);    if (c < 0x20 || c >= 0x7f || tspecials.indexOf(c) != -1)return false;}return true;    }
During information transmission, the cookie is stored in the HTTP Response Header. To set a cookie in JSP, you need to send the following information to the server:

HTTP/1.1 200 OKDate: Fri, 04 Feb 2014 21:03:38 GMTServer: Apache/1.3.9 (UNIX) PHP/4.0b3Set-Cookie: name=xyz; expires=Friday, 14-Feb-07 22:03:38 GMT;                  path=/; domain=tutorialspoint.comConnection: closeContent-Type: text/html
If the browser is configured to store cookies, it will save the information until it expires. If any page accessed by the user matches the path and domain name in the cookie, the browser will send the cookie back to the server. The browser header looks like the following
GET / HTTP/1.0Connection: Keep-AliveUser-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)Host: zink.demon.co.uk:1126Accept: image/gif, */*Accept-Encoding: gzipAccept-Language: enAccept-Charset: iso-8859-1,*,utf-8Cookie: name=xyz



So how do we create and use cookies in JSP?

1) create a cookie object:Call the cookie constructor and use a cookie name and value as parameters. They are strings.

2) set the validity period:The setmaxage () function indicates how long the cookie is valid (in seconds. The following operation sets the validity period to 24 hours.

3) Send the cookie to the HTTP Response Header:Call the response. addcookie () function to add cookies to the HTTP response header.

The following code stores the user name and password information in the cookie.

Web. XML (population of web programs)

<servlet>    <servlet-name>Cookie</servlet-name>    <servlet-class>com.qzp.servlet.cookieServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>Cookie</servlet-name>    <url-pattern>/cookie</url-pattern>  </servlet-mapping>

Cookietest. jsp

<Body> <form action = "cookie" method = "Post"> Username: <input type = "text" name = "name"> password: <input type = "password" name = "password"> <input type = "Submit" value = "login"> </form> </body>

Create a cookie in the background and set the cookie code. The cookie value is added to the local file through the response header.
Public class cookieservlet extends httpservlet {@ overrideprotected void doget (httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {This. doget (req, resp) ;}@ overrideprotected void dopost (httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {// todo auto-generated method stubstring name = req. getparameter ("name"); string Password = req. getparameter ("password"); // stores the cookie cookie1 = new cookie ("username", name) as a key-value pair; cookie cookie2 = new cookie ("psw ", password); // set the expiration time to 24 hours cookie1.setmaxage (60*60*24); cookie2.setmaxage (60*60*24); // Add cookieresp to the response header. addcookie (cookie1); resp. addcookie (cookie2); req. getrequestdispatcher ("cookieresult. JSP "). forward (req, resp );}}
Cookieresult. JSP: obtains the cookie value through an El expression in the format of $ {cookie. key. value} (if you are not familiar with El expressions, please refer to my next tutorial)

<body><center>The user name and password you entered are returned. (Of course, it is not safe to put the password value in the cookie. We recommend that you put it in the session server. Here we only use it for demonstration)

In addition, the cookie array is used to output all the cookie values stored locally. For example, the following code can traverse all the cookie values locally (Out is a built-in JSP object and can be used to print the output to the page)

<Center> 



In-depth analysis and research on cookies

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.