Detailed explanation of how JSP processes cookies

Source: Internet
Author: User

1. What are Cookies?

As we all know, the browser communicates with the WEB server over HTTP. When a user sends a page request, the WEB server simply responds, close the connection to the user. Therefore, when a request is sent to the WEB server, whether it is the first visit or not, the server treats it as the first visit. Such a bad thing can be imagined. To make up for this defect, Netscape has developed an effective cookie tool to store the recognition information of a user. Therefore, they are nicknamed "cookies ". Cookies are a means for WEB servers to store information on visitors' hard disks through Browsers: Netscape navigatoruses a local file named cookies.txt to store Cookie Information received from all sites; the IE browser saves the Cookie information in a directory similar to C: \ windows \ cookies. When a user accesses a site again, the server requires the browser to search for and return the Cookie information sent previously to identify the user.

Cookies bring many benefits to websites and users:

1. Cookie allows the site to track the number of visits, the last visit time, and the path of visitors to the site

2. Cookies can tell online advertisers the number of clicks on ads, so that they can deliver ads more accurately.

3. When the Cookie validity period is not reached, the Cookie enables users to access some websites they have browsed without entering their passwords and usernames.

4. Cookies can help Websites collect users' personal data for various personalized services.

In JSP, we can also use cookies to write some powerful applications.

Next, I would like to introduce how to use JSP to process and create cookies.

Ii. How to Create a Cookie

After talking about this, you must be curious about how JSP creates cookies. JSP uses the following syntax to create a Cookie:

Cookie cookie_name = new Cookie ("Parameter", "Value ");

For example, Cookie newCookie = new Cookie ("username", "waynezheng"); response. addCookie (newCookie );

Explanation: JSP calls the constructor Cookie (name, value) corresponding to the Cookie object to create a Cookie with a proper name and value, then, the Cookie can be added to the Set-Cookie response header Through the addCookie method of HttpServletResponse. In this example, the Cookie object has two string parameters: username and waynezheng. Note that the name and value cannot contain white spaces or the following characters :@:;? , "/[] () =

Iii. Attributes of JSP Cookie Processing

Some friends have asked me again: I know how to create cookies? Yes, it is not enough to know how to create a Cookie without knowing how to use it. In JSP, the Program sets various attributes through cookie. setXXX and reads the cookie attributes using cookie. getXXX. The main attributes and methods of the Cookie are listed below for your reference:

Type Method Name Explanation
String GetComment () Return the comment in the cookie. If there is no comment, a null value is returned.
String GetDomain () Returns the domain name applicable to the cookie in the Cookie. the getDomain () method can be used to instruct the browser to return the Cookie to other servers in the same domain. Generally, the Cookie only returns the server with the same name as the server that sent the Cookie. Note that the domain name must start with a dot such as .yesky.com)
Int GetMaxAge () Returns the maximum time before the Cookie expires, in seconds.
String GetName () Returns the Cookie name. The name and value are two parts that we always care about. The author will introduce getName/setName in detail later.
String GetPath () Return the applicable path of the Cookie. If no path is specified, the Cookie will be returned to all the pages in the directory of the current page and Its subdirectories.
Boolean GetSecure () If the browser sends cookies through the security protocol, the return value is true. If the browser uses the standard protocol, the return value is false.
String GetValue () Return the Cookie value. The author will also introduce getValue/setValue in detail later.
Int GetVersion () Return the Protocol version that the Cookie complies.
Void SetComment (String purpose) Set the comment in the cookie.
Void SetDomain (String pattern) Set the domain name for the cookie in the Cookie
Void SetMaxAge (int expiry) Set the Cookie expiration time in seconds.
Void SetPath (String uri) Specifies the applicable path of the Cookie.
Void SetSecure (boolean flag) Indicates the security protocol used by the browser, such as HTTPS or SSL.
Void SetValue (String newValue) Set a new value after the cookie is created.
Void SetVersion (int v) Set the Protocol version that the Cookie complies.

4. Read client cookies

When processing a Cookie in JSP, you must create a Cookie before sending the Cookie to the client, and then use the addCookie method to send an HTTP Header. JSP will call request. getCookies () to read the Cookie from the client. The getCookies () method returns an array of Cookie objects corresponding to the content in the HTTP request header. You only need to access each element of the array cyclically, call the getName method to check the names of each Cookie until the target Cookie is found, call the getValue method for the Cookie to obtain the value associated with the specified name.

For example

 
 
  1. <%
  2. StringUserName=Request. GetParameter ("username"); // obtain from the submitted HTML form, username
  3. CookieTheUsername=NewCookie ("username", userName); // create a Cookie with "username", userName value/pair
  4. Response. addCookie (theUsername );
  5. %> 
  6. ..............
  7. <%
  8. Cookie myCookie [] = request. getCookies (); // create a Cookie object Array
  9. For (intN=0;N=Cookie. Length-1; I ++); // sets up a loop to access each element of the Cookie object array.
  10. CookieNewCookie=MyCookie[N];
  11. If (newCookie. getName (). equals ("username"); // determines whether the element value is a value in username.
  12. {%> 
  13. Hello,<% = NewCookie. getValue () %>! // If you find it, say hello to him.
  14. <%}
  15. %> 

Set the Cookie existence time and delete the Cookie in JSP. Use the setMaxAge (int expiry) method to set the Cookie existence time. The expiry parameter should be an integer. A positive value indicates that the cookie will expire after so many seconds. Note that this value is the maximum time for the cookie to exist, rather than the current time when the Cookie exists. A negative value indicates that when the browser is closed, the Cookie will be deleted. If the value is zero, the Cookie is to be deleted. For example:

 
 
  1. <%  
  2.  Cookie deleteNewCookie=new Cookie("newcookie",null);  
  3.  deleteNewCookie.setMaxAge(0);  
  4.  deleteNewCookie.setPath("/");   
  5.  response.addCookie(deleteNewCookie);  
  6. %> 

This is the process for JSP to process cookies. However, in the practical development process, the project requirements and user habits should also be considered.

  1. JSP garbled Problem and Solution
  2. Advantages of JSP: Application Scope and Performance Comparison
  3. How to Set Up JSP development and running environment
  4. Servlets and JSP Best Practices
  5. Configuration of three connection strings in JSP

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.