Servlets 简明教程
Servlets - Cookies Handling
Cookie 是存储在客户端计算机上的文本文件,用于跟踪各种信息。Java Servlet 透明地支持 HTTP Cookie。
Cookies are text files stored on the client computer and they are kept for various information tracking purpose. Java Servlets transparently supports HTTP cookies.
识别返回用户涉及三个步骤 −
There are three steps involved in identifying returning users −
-
Server script sends a set of cookies to the browser. For example name, age, or identification number etc.
-
Browser stores this information on local machine for future use.
-
When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.
本章将教您如何设置或重置 Cookie、如何访问它们以及如何删除它们。
This chapter will teach you how to set or reset cookies, how to access them and how to delete them.
The Anatomy of a Cookie
Cookie 通常设置在 HTTP 标头中(尽管 JavaScript 也可以在浏览器上直接设置 Cookie)。设置 Cookie 的 servlet 可能会发送类似以下内容的标头 −
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A servlet that sets a cookie might send headers that look something like this −
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT;
path = /; domain = tutorialspoint.com
Connection: close
Content-Type: text/html
如您所见,Set-Cookie 标头包含一个名称值对、一个 GMT 日期、一个路径和一个域名。名称和值将经过 URL 编码。expires 字段是指示浏览器在给定时间和日期后“忘记”Cookie 的指令。
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time and date.
如果浏览器配置为存储 Cookie,它将保留此信息,直至过期日期。如果用户在任何匹配该 Cookie 的路径和域名的页面上指向浏览器,它将向服务器重新发送该 Cookie。浏览器的标头可能看起来像 −
If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser’s headers might look something 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
然后 Servlet 可以通过请求方法 request.getCookies() 访问该 Cookie,这会返回 Cookie 对象的数组。
A servlet will then have access to the cookie through the request method request.getCookies() which returns an array of Cookie objects.
Servlet Cookies Methods
以下是可以在 Servlet 中操作 Cookie 时使用的有用方法列表。
Following is the list of useful methods which you can use while manipulating cookies in servlet.
Sr.No. |
Method & Description |
1 |
*public void setDomain(String pattern) * This method sets the domain to which cookie applies, for example tutorialspoint.com. |
2 |
*public String getDomain() * This method gets the domain to which cookie applies, for example tutorialspoint.com. |
3 |
public void setMaxAge(int expiry) This method sets how much time (in seconds) should elapse before the cookie expires. If you don’t set this, the cookie will last only for the current session. |
4 |
public int getMaxAge() This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown. |
5 |
public String getName() This method returns the name of the cookie. The name cannot be changed after creation. |
6 |
*public void setValue(String newValue) * This method sets the value associated with the cookie |
7 |
*public String getValue() * This method gets the value associated with the cookie. |
8 |
*public void setPath(String uri) * This method sets the path to which this cookie applies. If you don’t specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories. |
9 |
public String getPath() This method gets the path to which this cookie applies. |
10 |
public void setSecure(boolean flag) This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL) connections. |
11 |
*public void setComment(String purpose) * This method specifies a comment that describes a cookie’s purpose. The comment is useful if the browser presents the cookie to the user. |
12 |
public String getComment() This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment. |
Setting Cookies with Servlet
通过 Servlet 设置 Cookie 涉及三个步骤 −
Setting cookies with servlet involves three steps −
(1) Creating a Cookie object − 使用 Cookie 名称和 Cookie 值调用 Cookie 构造函数,两者均为字符串。
(1) Creating a Cookie object − You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.
Cookie cookie = new Cookie("key","value");
记住,名称或值都不应包含空格或以下任何字符 −
Keep in mind, neither the name nor the value should contain white space or any of the following characters −
[ ] ( ) = , " / ? @ : ;
(2) Setting the maximum age − 使用 setMaxAge 指定 Cookie 应有效多长时间(以秒为单位)。以下将设置一个 24 小时的 Cookie。
(2) Setting the maximum age − You use setMaxAge to specify how long (in seconds) the cookie should be valid. Following would set up a cookie for 24 hours.
cookie.setMaxAge(60 * 60 * 24);
(3) Sending the Cookie into the HTTP response headers − 您使用 response.addCookie 在 HTTP 响应头中添加 cookie,如下所示:
(3) Sending the Cookie into the HTTP response headers − You use response.addCookie to add cookies in the HTTP response header as follows −
response.addCookie(cookie);
Example
我们修改我们的 Form Example 以设置 first 和 last name 的 cookie。
Let us modify our Form Example to set the cookies for first and last name.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));
// Set expiry date after 24 Hrs for both the cookies.
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
// Add both the cookies in the response header.
response.addCookie( firstName );
response.addCookie( lastName );
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Setting Cookies Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head>
<title>" + title + "</title>
</head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body>
</html>"
);
}
}
编译上面的 servlet HelloForm 并创建 web.xml 文件中的相应条目,最后尝试以下 HTML 页面以调用 servlet。
Compile the above servlet HelloForm and create appropriate entry in web.xml file and finally try following HTML page to call servlet.
<html>
<body>
<form action = "HelloForm" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
将上面的 HTML 内容保留在 Hello.htm 文件中,并将其放到 <Tomcat 安装目录>/webapps/ROOT 目录中。在您访问时 [role="bare"] [role="bare"]http://localhost:8080/Hello.htm ,以下是上面表单的实际输出。
Keep above HTML content in a file Hello.htm and put it in <Tomcat-installationdirectory>/webapps/ROOT directory. When you would access [role="bare"]http://localhost:8080/Hello.htm, here is the actual output of the above form.
尝试输入 First Name 和 Last Name,然后点击提交按钮。将显示您的屏幕上的 first name 和 last name,同时将设置两个 cookies(firstName 和 lastName),下次按下提交按钮时将传回服务器。
Try to enter First Name and Last Name and then click submit button. This would display first name and last name on your screen and same time it would set two cookies firstName and lastName which would be passed back to the server when next time you would press Submit button.
下一部分将向您解释如何在 Web 应用程序中访问这些 cookie。
Next section would explain you how you would access these cookies back in your web application.
Reading Cookies with Servlet
要读取 cookie,需要通过调用 HttpServletRequest 的 getCookies() 方法,创建一个 javax.servlet.http.Cookie 对象的数组。然后循环数组,并使用 getName() 和 getValue() 方法来访问每个 cookie 和关联的值。
To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies() method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value.
Example
我们读取在先前示例中设置的 cookie −
Let us read cookies which we have set in previous example −
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class ReadCookies extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with this domain
cookies = request.getCookies();
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Cookies Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" );
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>");
}
out.println("</body>");
out.println("</html>");
}
}
编译上面 servlet ReadCookies 并创建 web.xml 文件中的相应条目。如果您将 first_name cookie 设置为“John”,将 last_name cookie 设置为“Player”,则运行 [role="bare"] [role="bare"]http://localhost:8080/ReadCookies 将显示以下结果 −
Compile above servlet ReadCookies and create appropriate entry in web.xml file. If you would have set first_name cookie as "John" and last_name cookie as "Player" then running [role="bare"]http://localhost:8080/ReadCookies would display the following result −
Found Cookies Name and Value
Name : first_name, Value: John
Name : last_name, Value: Player
Delete Cookies with Servlet
删除 cookie 非常简单。如果您希望删除 cookie,只需按照以下三个步骤操作:
To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps −
-
Read an already existing cookie and store it in Cookie object.
-
Set cookie age as zero using setMaxAge() method to delete an existing cookie
-
Add this cookie back into response header.
Example
以下示例将删除名为“first_name”的现有 cookie,当您下次运行 ReadCookies servlet 时,它将为 first_name 返回空值。
The following example would delete and existing cookie named "first_name" and when you would run ReadCookies servlet next time it would return null value for first_name.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class DeleteCookies extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with this domain
cookies = request.getCookies();
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Delete Cookies Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" );
if( cookies != null ) {
out.println("<h2> 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>");
}
out.println("</body>");
out.println("</html>");
}
}
编译上面 servlet DeleteCookies 并创建 web.xml 文件中的相应条目。现在,运行 [role="bare"] [role="bare"]http://localhost:8080/DeleteCookies 将显示以下结果 −
Compile above servlet DeleteCookies and create appropriate entry in web.xml file. Now running [role="bare"]http://localhost:8080/DeleteCookies would display the following result −
Cookies Name and Value
Deleted cookie : first_name
Name : first_name, Value: John
Name : last_name, Value: Player
现在,尝试运行 [role="bare"] [role="bare"]http://localhost:8080/ReadCookies ,它将只显示一个如下所示的 cookie −
Now try to run [role="bare"]http://localhost:8080/ReadCookies and it would display only one cookie as follows −
Found Cookies Name and Value
Name : last_name, Value: Player
您可以在 Internet Explorer 中手动删除 cookie。从工具菜单开始,然后选择 Internet 选项。要删除所有 cookie,请按删除 Cookies。
You can delete your cookies in Internet Explorer manually. Start at the Tools menu and select Internet Options. To delete all cookies, press Delete Cookies.