Cookies are text files stored on the client computer, and they save a large amount of track information. Based on servlet technology, JSP can obviously provide support for HTTP cookies.
There are typically three steps to identifying repeat customers:
The server script sends a series of cookies to the browser. Such as name, age, ID number, etc.
The browser stores this information locally on the computer in case it is needed.
The next time the browser sends any request to the server, it will also send these cookie information to the server, and then the server uses this information to identify the user or do other things.
This section will teach you how to set or reset cookies, how to access them and how to delete them.
Cookies are usually set in HTTP headers (although JavaScript can set cookies directly in the browser). In JSP, setting a cookie requires sending the following information header to the server:
HTTP/1.1 200 OKDate: Fri, 04 Feb 2000 21:03:38 GMTServer: Apache/1.3.9 (UNIX) PHP/4.0b3Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03: 38 GMT; path=/; domain=tutorialspoint.comConnection: closeContent-Type: text/html
As you can see, the Set-Cookie header contains a key-value pair, a GMT (Greenwich Mean Time) time, a path, and a domain name. Key-value pairs will be encoded as URLs. The expiry date field is an instruction that tells the browser after which time it can clear this cookie.
If your browser is configured to store cookies, it will retain this information until it expires. If any page visited by the user matches the path and domain name in the cookie, the browser will re-send the cookie back to the server. The header on the browser side looks like this:
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
JSP scripts access these cookies through the getCookies() method in the request object. This method returns an array of Cookie objects.
The following table lists the commonly used methods in Cookie objects:
serial number | Method & Description |
---|---|
1 | public void setDomain(String pattern) sets the domain name of the cookie, such as w3cschool.cn |
2 | public String getDomain() gets the domain name of the cookie, such as w3cschool.cn |
3 | public void setMaxAge(int expiry) sets the cookie validity period in seconds. The default validity period is the survival time of the current session. |
4 | public int getMaxAge() gets the cookie validity period in seconds, the default is -1, indicating that the cookie will live until the browser is closed |
5 | public String getName() returns the name of the cookie. The name cannot be modified after it is created. |
6 | public void setValue(String newValue) sets the value of cookie |
7 | public String getValue() gets the value of the cookie |
8 | public void setPath(String uri) sets the cookie path, which defaults to all URLs in the current page directory and all subdirectories in this directory. |
9 | public String getPath() gets the path of the cookie |
10 | public void setSecure(boolean flag) indicates whether the cookie should be encrypted for transmission |
11 | public void setComment(String purpose) sets the comment to describe the purpose of the cookie. Annotations can be useful when the browser displays the cookie to the user |
12 | public String getComment() returns a comment describing the purpose of the cookie, or null if there is none |
Setting cookies using JSP involves three steps:
(1) Create a Cookie object: Call the Cookie constructor, using a cookie name and value as parameters, both of which are strings.
Cookie cookie = new Cookie("key","value");
It is important to remember that neither the name nor the value can contain spaces or the following characters:
[ ] ( ) = , " / ? @ : ;
(2) Set the validity period: Call the setMaxAge() function to indicate how long (in seconds) the cookie is valid. The following operation sets the validity period to 24 hours.
cookie.setMaxAge(60*60*24);
(3) Send cookies to the HTTP response header: call the response.addCookie() function to add cookies to the HTTP response header.
response.addCookie(cookie);
<% // Set cookies for first_name and last_name Cookie firstName = new Cookie("first_name", request.getParameter("first_name")); Cookie lastName = new Cookie("last_name",request.getParameter("last_name")); //Set the cookie expiration time to 24 hours. firstName.setMaxAge(60*60*24); lastName.setMaxAge(60*60*24); // Add cookie to the response header response.addCookie( firstName ); response.addCookie( lastName ); %><html>< head><title>Setting Cookies</title></head><body><center><h1>Setting Cookies</h1></center><ul><li><p><b>First Name:</b><%= request.getParameter("first_name")%></p></li>< li><p><b>Last Name:</b> <%= request.getParameter("last_name")%></p></li></ul></body></html>
Place the above file in the <Tomcat installation directory>/webapps/ROOT directory, and then visit http://localhost:8080/hello.jsp, you will get the following output:
Try entering First Name and Last Name, and then click the submit button. It will display first name and last name on your screen, and set two cookies, first name and last name, which will be sent to the server the next time you click the submit button. .
To read cookies, you need to call the request.getCookies() method to obtain an array of javax.servlet.http.Cookie objects, then iterate through the array and use the getName() method and getValue() method to obtain each cookie. name and value.
Let's read the cookies from the previous example.
<html><head><title>Reading Cookies</title></head><body><center><h1>Reading Cookies</h1></center><% Cookie cookie = null; Cookie[] cookies = null; // Get cookie data, which is an array cookies = request.getCookies(); if( cookies != null ){ out.println("<h2> Found Cookies Name and Value</h2>"); for ( int i = 0; i < cookies.length; i++){ cookie = cookies[i]; out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue ( )+" <br/>"); } }else{ out.println("<h2>No cookies founds</h2>"); }%></body></html>
If you set the first name cookie to "John" and the last name to "Player" and visit http://localhost:8080/main.jsp, you will get the following output:
Found Cookies Name and ValueName : first_name, Value: John Name : last_name, Value: Player
Deleting cookies is very easy. If you want to delete a cookie, just follow the steps given below:
Get an existing cookie and store it in the Cookie object.
Set the cookie expiry date to 0.
Add this cookie back to the response header.
The following program deletes a cookie named "first_name". The next time you run main.jsp, first_name will be null.
<html><head><title>Reading Cookies</title></head><body><center> <h1>Reading Cookies</h1></center><% Cookie cookie = null; Cookie[] cookies = null; // Get the cookies under the current domain name, which is an array cookies = request.getCookies(); if( cookies != null ){ out.println("<h2> Found Cookies Name and Value</h2>"); for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; if((cookie.getName( )).compareTo("first_name") == 0 ){ cookie.setMaxAge(0); response.addCookie (cookie); out.print("Deleted cookie: " + cookie.getName( ) + "<br/>"); } out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" <br/>"); } }else{ out.println( "<h2>No cookies founds</h2>"); }%></ body></html>
Accessing it will give you the following output:
Cookies Name and ValueDeleted cookie : first_nameName : first_name, Value: JohnName : last_name, Value: Player
Visit http://localhost:8080/main.jsp again and you will get the following results:
Found Cookies Name and ValueName : last_name, Value: Player
You can also delete cookies manually in your browser. Click the Tools menu item, then select Internet Options, click Delete Cookies to delete all cookies.