Create cookies with JSP
What is a cookie?
As you know, the browser communicates with the Web server using the HTTP protocol, and when a user makes a page request, the WEB server simply responds, and then closes the connection to the user. So when a request is sent to a Web server, whether it is the first visit or not, the server treats it as if it was the first time, so the bad things can be imagined. To make up for this flaw, Netscape has developed cookies as an effective tool for saving information about a user's identity, so people are nicknamed "cookies". Cookies are a way for a Web server to store information on a visitor's hard disk through a browser: Netscape Navigator Use a local file named Cookies.txt to save cookie information received from all sites, and IE browser to store cookie information in a directory similar to C:\windows\cookies. When a user accesses a site again, the server will require the browser to look up and return the previously sent cookie information to identify the user.
Cookies bring a lot of benefits to websites and users:
1. Cookies enable the site to track the number of visits to a particular visitor, the last access time, and the path that visitors enter the site
2. Cookies can tell online advertisers how many times they have been clicked to advertise more accurately.
3. When the cookie expires, the cookie enables the user to enter a site that has been browsed without typing the password and username
4. Cookies can help the site to statistical user profile to achieve a variety of personalized services
In the JSP, we can also use cookies to write some powerful applications.
Creating cookies
import="javax.servlet.http.Cookie"
Having said so much, you must be very interested to know how JSP creates cookies. A JSP uses the following syntax format to create a cookie:
Cookie cookie_name =new Cookie("Parameter","Value");
For example:
Cookie username_Cookie =new Cookie("username","waynezheng");
response.addCookie(username_Cookie);
Explanation: A JSP is a call to the cookie object's corresponding constructor cookie (name,value) to create a cookie with the appropriate name and value. The following cookie can be added to the Set-cookie answer header via the HttpServletResponse Addcookie method, in this case the cookie object has two string parameters: Username,waynezheng. Note that neither the name nor the value can contain whitespace characters and the following characters:
@ : ;? , " / [ ] ( ) =