📅  最后修改于: 2020-11-12 05:41:18             🧑  作者: Mango
Cookies是存储在客户端计算机上的文本文件,它们被保留以用于各种信息跟踪目的。 Java Servlet透明地支持HTTP cookie。
识别回头用户涉及三个步骤-
服务器脚本将一组cookie发送到浏览器。例如姓名,年龄或身份证号码等。
浏览器将此信息存储在本地计算机上,以备将来使用。
当下一次浏览器向Web服务器发送任何请求时,它会将那些cookie信息发送到服务器,并且服务器使用该信息来识别用户。
本章将教您如何设置或重置cookie,如何访问它们以及如何删除它们。
Cookie通常是在HTTP标头中设置的(尽管JavaScript也可以直接在浏览器中设置Cookie)。设置cookie的servlet可能会发送类似于以下内容的标头-
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。
如果将浏览器配置为存储cookie,则它将保留此信息直到到期日期。如果用户将浏览器指向与cookie的路径和域匹配的任何页面,它将把cookie重新发送到服务器。浏览器的标题可能看起来像这样-
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对象数组。
以下是在servlet中操作cookie时可以使用的有用方法的列表。
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. |
使用servlet设置cookie涉及三个步骤-
(1)创建一个Cookie对象-您用一个cookie名称和一个cookie值调用cookie构造函数,它们都是字符串。
Cookie cookie = new Cookie("key","value");
请记住,名称和值均不应包含空格或以下任何字符-
[ ] ( ) = , " / ? @ : ;
(2)设置最长期限-您使用setMaxAge指定cookie有效的时间(以秒为单位)。接下来将设置一个24小时的cookie。
cookie.setMaxAge(60 * 60 * 24);
(3)将Cookie发送到HTTP响应标头中-您可以使用response.addCookie在HTTP响应标头中添加cookie,如下所示-
response.addCookie(cookie);
让我们修改“表单示例”以设置名字和姓氏的cookie。
// 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 =
""-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"\n" +
"
" + title + "
\n" +
"\n" +
"" + title + "
\n" +
"\n" +
" - First Name: "
+ request.getParameter("first_name") + "\n" +
"
- Last Name: "
+ request.getParameter("last_name") + "\n" +
"
\n" +
"
"
);
}
}
编译上面的servlet HelloForm,并在web.xml文件中创建适当的条目,最后尝试在HTML页面之后调用servlet。
将以上HTML内容保留在文件Hello.htm中,并将其放在
尝试输入名字和姓氏,然后单击提交按钮。这将在屏幕上显示名字和姓氏,同时将设置两个cookie firstName和lastName,这将在下次您单击Submit按钮时传递回服务器。
下一节将向您说明如何在Web应用程序中重新访问这些Cookie。
要读取cookie,您需要通过调用HttpServletRequest的getCookies()方法来创建javax.servlet.http.Cookie对象的数组。然后循环遍历数组,并使用getName()和getValue()方法访问每个cookie和关联的值。
让我们阅读在上一个示例中设置的cookie-
// 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 =
""-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"\n" +
"" + title + " \n" +
"\n" );
if( cookies != null ) {
out.println(" Found Cookies Name and Value
");
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( ) + "
");
}
} else {
out.println("No cookies founds
");
}
out.println("");
out.println("");
}
}
编译上面的Servlet ReadCookies,并在web.xml文件中创建适当的条目。如果将first_name cookie设置为“ John”,将last_name cookie设置为“ Player”,则运行http:// localhost:8080 / ReadCookies将显示以下结果-
Found Cookies Name and Value
Name : first_name, Value: John
Name : last_name, Value: Player
删除Cookie非常简单。如果您想删除Cookie,则只需遵循以下三个步骤-
读取一个已经存在的cookie并将其存储在Cookie对象中。
使用setMaxAge()方法将Cookie年龄设为零,以删除现有的Cookie
将此Cookie重新添加到响应标头中。
以下示例将删除现有的名为“ first_name”的cookie,并且当您下次运行ReadCookies servlet时,它将为first_name返回null值。
// 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 =
""-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"\n" +
"" + title + " \n" +
"\n" );
if( cookies != null ) {
out.println(" Cookies Name and Value
");
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( ) + "
");
}
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+"
");
}
} else {
out.println("No cookies founds
");
}
out.println("");
out.println("");
}
}
在Servlet DeleteCookies上方进行编译,并在web.xml文件中创建适当的条目。现在运行http:// localhost:8080 / DeleteCookies将显示以下结果-
Cookies Name and Value
Deleted cookie : first_name
Name : first_name, Value: John
Name : last_name, Value: Player
现在尝试运行http:// localhost:8080 / ReadCookies ,它将仅显示一个cookie,如下所示-
Found Cookies Name and Value
Name : last_name, Value: Player
您可以在Internet Explorer中手动删除Cookie。从“工具”菜单开始,然后选择“ Internet选项”。要删除所有cookie,请按Delete Cookies。