English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Cookies are text files stored on the client machine, which contain a large amount of trace information. Based on Servlet technology, JSP can obviously provide support for HTTP cookies.
There are usually three steps to identify returning customers:
The server script sends a series of cookies to the browser. For example, name, age, ID number, etc.
The browser stores this information locally for future use.
When the browser sends any request to the server next time, it will send these cookie information to the server at the same time, and then the server uses this information to identify the user or do other things.
This chapter will teach you how to set or reset cookies, as well as how to access them and how to delete them.
The handling of JSP cookies requires encoding and decoding of Chinese characters, the method is as follows:
String str = java.net.URLEncoder.encode("Chinese","UTF-8")-8); //Encoding String str = java.net.URLDecoder.decode("Encoded String","UTF-8")-8); // Decoding
Cookies are usually set in the HTTP information header (although JavaScript can set cookies directly in the browser). In JSP, to set a cookie, you need to send the following information header to the server:
HTTP/1.1 200 OK Date: Fri, 04 Feb 2015 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name=w3codebox; expires=Friday, 04-Feb-17 22:03:38 GMT; path=/; domain=oldtoolbag.com Connection: close Content-Type: text/html
Just as you can see, Set-The Cookie information header contains a key-value pair, a GMT (Greenwich Mean Time) time, a path, and a domain. The key-value pair is encoded as a URL. The expiration domain is an instruction that tells the browser when it can clear this cookie.
If the browser is configured to store cookies, it will save this information until it expires. If any page accessed by the user matches the path and domain in the cookie, the browser will send this cookie back to the server. The information header on the browser side looks like this:
GET / HTTP/1.0 Connection: Keep-Alive User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc) Host: zink.demon.co.uk:1126 Accept: image/gif, */* Accept-Encoding: gzip Accept-Language: en Accept-Charset: iso-8859-1,*,utf-8 Cookie: name=xyz
JSP scripts access these cookies through the getCookies() method in the request object, which returns an array of Cookie objects.
The following table lists the commonly used methods in the Cookie object:
Serial number | Method & Description |
---|---|
1 | public void setDomain(String pattern) Set the domain of the cookie, for example, oldtoolbag.com |
2 | public String getDomain() Get the domain of the cookie, for example, oldtoolbag.com |
3 | public void setMaxAge(int expiry) Set the validity period of the cookie, in seconds, the default validity period is the lifetime of the current session |
4 | public int getMaxAge() Get the validity period of the cookie, in seconds, the default is-1 , indicating that the cookie will last until the browser is closed |
5 | public String getName() Return the name of the cookie, the name cannot be modified after it is created |
6 | public void setValue(String newValue) Set the value of the cookie |
7 | public String getValue() Get the value of the cookie |
8 | public void setPath(String uri) Set the path of the cookie, the default is all URLs under the current page directory, as well as all subdirectories under this directory |
9 | public String getPath() Get the path of the cookie |
10 | public void setSecure(boolean flag) Specify whether the cookie should be transmitted in an encrypted manner |
11 | public void setComment(String purpose) Set the comment describing the purpose of the cookie. The comment will be very useful when the browser displays the cookie to the user |
12 | public String getComment() Return comments describing the purpose of the cookie, or null if there are none |
Using JSP to set a cookie involves three steps:
(1) Create a cookie object: Call the constructor of the cookie, using a cookie name and value as parameters, both of which are strings.
Cookie cookie = new Cookie("key","value");
Please 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);
(3Send the cookie to the HTTP response header:Call the response.addCookie() function to add a cookie to the HTTP response header.
response.addCookie(cookie);
The code of the main.jsp file is as follows:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.net."*" %> <% // encoding, to solve garbled characters. String str = URLEncoder.encode(request.getParameter("name"),"utf-8); // Set name and url cookies Cookie name = new Cookie("name", str); Cookie url = new Cookie("url", request.getParameter("url")); // Set cookie expiration time to24hours. name.setMaxAge(60*60*24); url.setMaxAge(60*60*24); // Add cookie to the response header response.addCookie(name); response.addCookie(url); %> <html> <head> <title>Set Cookie</title> </head> <body> <h1>Set Cookie</h1> <ul> <li><p><b>Website name:</b>/b> <%= request.getParameter("name") %> </p></li> <li><p><b>URL:</b>/b> <%= request.getParameter("url") %> </p></li> </ul> </body> </html>
The following is a simple HTML form that submits client data to the main.jsp file using the GET method and sets cookies:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Basic Tutorial Website(oldtoolbag.com)</title> </head> <body> <form action="main.jsp" method=GET> Site name: <input type="text" name="name"> <br /> URL: <input type="text" name="url" /> <input type="submit" value="Submit" /> </form> </body> </html>
Save the above HTML code to a test.htm file.
Place this file in the current jsp project's WebContent directory (in the same directory as main.jsp).
By accessing http://localhost:8080/testjsp/Submit form data to the main.jsp file as shown in test.html:
Try entering "site name" and "URL", then click the submit button, it will display "site name" and "URL" on your screen, and set two cookies for "site name" and "URL".
To read a cookie, you need to call the request.getCookies() method to get an array of javax.servlet.http.Cookie objects, then iterate over this array, use the getName() and getValue() methods to get the name and value of each cookie.
Let's read the cookie from the previous example, the following is the code of cookie.jsp file:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.net."*" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Get Cookie</title> </head> <body> <% Cookie cookie = null; Cookie[] cookies = null; // Get cookies data, it is an array cookies = request.getCookies(); if( cookies != null ){ out.println("<h2> Find Cookie Name and Value</h2">); for (int i = 0; i < cookies.length; i++{ cookie = cookies[i]; out.print("Parameter name: " + cookie.getName()); out.print("<br>); out.print("Parameter value: " + -8) +" <br>" out.print("------------------------------------<br>); } } out.println("<h2>No cookies found</h2">); } %> </body> </html>
After the browser visits, the output result is:
Deleting a cookie is very simple. If you want to delete a cookie, just follow the steps below:
Get an existing cookie and store it in the Cookie object.
Set the expiration time of the cookie to 0.
Re-add this cookie to the response header.
The following program deletes a cookie named "name", when you run cookie.jsp for the second time, name will be null.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.net."*" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Get Cookie</title> </head> <body> <% Cookie cookie = null; Cookie[] cookies = null; // Get cookies under the current domain, it is an array cookies = request.getCookies(); if( cookies != null ){ out.println("<h2> Find Cookie Name and Value</h2">); for (int i = 0; i < cookies.length; i++{ cookie = cookies[i]; if((cookie.getName( )).compareTo("name") == 0 ){ cookie.setMaxAge(0); response.addCookie(cookie); out.print("Delete Cookie: " + cookie.getName( ) + "<br/">); } out.print("Parameter name: " + cookie.getName()); out.print("<br>); out.print("Parameter value: " + -8) +" <br>" out.print("------------------------------------<br>); } } out.println("<h2>No cookies found</h2">); } %> </body> </html>
Access through the browser, the output result is:
Visit http: again//localhost:8080/testjsp/The result after running cookie.jsp will be as follows:
You can see that the cookie named "name" has disappeared.
You can also manually delete cookies in the browser. In Internet Explorer, click on the Tools menu item, then select Internet Options, click Delete Cookies to delete all cookies.