在本章中,我们将讨论jsp中的cookie处理。 cookie是存储在客户端计算机上的文本文件,它们用于各种信息的跟踪。jsp透明地支持使用底层servlet技术的http cookie。
识别和返回用户信息有三个步骤 -
- 服务器脚本将一组cookie发送到浏览器。例如姓名,年龄或身份证号等
- 浏览器将此信息存储在本地机器上以备将来使用。
- 当下一次浏览器向web服务器发送任何请求时,浏览器将这些cookie信息发送到服务器,服务器使用该信息来识别用户,或者也可以用于其他目的。
本章将介绍如何设置或重置cookie,如何访问它们以及如何使用jsp程序来删除它们。
cookie剖析
cookie通常设置在http标头中(尽管javascript也可以直接在浏览器上设置cookie)。设置cookie的jsp响应头发送看起来类似这样 -
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 = 51frw.cn connection: close content-type: text/html
可以看到,set-cookie头包含name,gmt,path和domain的键值对。名称和值将被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
然后,jsp脚本将通过请求方法request.getcookies()访问cookie,该方法返回一个cookie对象数组。
servlet cookie方法
下表列出了与cookie对象相关联的有用方法,我们可以在jsp中操作cookie时调用它们。
编号 方法 描述| 1 | public void setdomain(string pattern) | 此方法设置适用cookie的域; 例如,51frw.cn。 |
| 2 | public string getdomain() | 此方法获取适用cookie的域; 例如,51frw.cn。 |
| 3 | public void setmaxage(int expiry) | 此方法设置在cookie过期之前经过多少时间(以秒为单位)。如果没有设置此项,cookie将仅持续到当前会话结束。 |
| 4 | public int getmaxage() | 此方法返回cookie的最大时间,以秒为单位指定。默认情况下,-1表示cookie将持续到浏览器关闭。 |
| 5 | public string getname() | 此方法返回cookie的名称。创建后不能更改名称。 |
| 6 | public void setvalue(string newvalue) | 此方法设置与cookie关联的值。 |
| 7 | public string getvalue() | 该方法获取与cookie相关联的值。 |
| 8 | public void setpath(string uri) | 此方法设置此cookie适用的路径。如果不指定路径,则将返回与当前页面以及所有子目录位于同一目录中的所有url的cookie。 |
| 9 | public string getpath() | 此方法获取此cookie应用的路径。 |
| 10 | public void setsecure(boolean flag) | 此方法设置布尔值,指示cookie是否应仅通过加密(即ssl)连接发送。 |
| 11 | public void setcomment(string purpose) | 此方法指定描述cookie目的的注释。 如果浏览器向用户显示cookie,则该注释很有用。 |
| 12 | public string getcomment() | 此方法返回描述此cookie目的的注释,如果cookie没有注释,则返回null。 |
使用jsp设置cookies
使用jsp设置cookie包括三个步骤 -
步骤1:创建一个cookie对象
指定cookie名称和cookie值调用cookie构造函数,这两者都是字符串。参考以下代码 -
cookie cookie = new cookie("key","value"); 请记住,名称和值都不应包含空格或任何以下字符 -
[ ] ( ) = , " / ? @ : ;
步骤2:设置最大有效时间
可以使用setmaxage指定cookie应该有效的时间(以秒为单位)。以下代码将设置一个24小时有效时间的cookie。
cookie cookie = new cookie("key","value");
cookie.setmaxage(60*60*24); 步骤3:将cookie发送到http响应头
使用response.addcookie在http响应标头中添加cookie,如下所示 -
cookie cookie = new cookie("key","value");
cookie.setmaxage(60*60*24);
response.addcookie(cookie); jsp操作cookies示例
打开eclipse,创建一个动态web项目:cookieshandling,其结构如下所示 -
假设要实现将用户提交上来的用户名和email设置到cookie中,并返回到客户端浏览器。请参考以下代码 -
文件:setcookies.jsp -
<%@ page language="java" contenttype="text/html; charset=utf-8"
pageencoding="utf-8"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>接收表单并设置cookies</title>
</head>
<body>
<%
// create cookies for first and last names.
cookie cookie1 = new cookie("username", request.getparameter("username"));
cookie cookie2 = new cookie("email", request.getparameter("email"));
// set expiry date after 24 hrs for both the cookies.
cookie1.setmaxage(60 * 60 * 24);
cookie2.setmaxage(60 * 60 * 24);
// add both the cookies in the response header.
response.addcookie(cookie1);
response.addcookie(cookie2);
%>
<div style="margin: auto; width: 80%;">
<center>
<h2>设置cookies</h2>
</center>
<ul>
<li><p>
<b>用户名:</b>
<%=request.getparameter("username")%>
</p></li>
<li><p>
<b>email:</b>
<%=request.getparameter("email")%>
</p></li>
</ul>
</div>
</body>
</html> 创建另一个显示表单的html文件:form.jsp,其内容如下所示 -
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>用户表单</title>
</head>
<body>
<div style="margin: auto; width: 80%">
<form action="setcookies.jsp" method="post">
用户名: <input type="text" name="username">
email: <input type="text" name="email" /> <input
type="submit" value="提交" />
</form>
</div>
</body>
</html> 当编写上面代码完成后,部署和运行这个项目,打开浏览器访问url:http://localhost:8080/cookieshandling/form.html , 在显示的表单中输入用户名和email,然后单击提交按钮。这将在屏幕上显示用户名和email,并且还将设置两个cookie:username和email。当下次访问页面时,这些cookie将被传回服务器。
分别在用户名和email输入框中填写:maxsu 和 maxsu@51frw.cn , 然后点击提交 -
在下一节中,我们将介绍如何在web应用程序中访问这些cookie。
使用jsp读取cookies
要使用jsp读取cookie,需要通过调用httpservletrequest的getcookies()方法来创建一个javax.servlet.http.cookie对象的数组。 然后循环遍历数组,并使用getname()和getvalue()方法来访问每个cookie和关联的值。
现在来看看如何读取前面的例子中设置的cookie,创建一个jsp文件:getcookies.jsp -
<%@ page language="java" contenttype="text/html; charset=utf-8"
pageencoding="utf-8"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>读取cookies</title>
</head>
<body>
<div style="margin: auto; width: 80%;">
<%
cookie cookie = null;
cookie[] cookies = null;
// get an array of cookies associated with the this domain
cookies = request.getcookies();
if (cookies != null) {
out.println("<h2>找到的cookie名称和值</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>");
}
%>
</div>
</body>
</html> 重新部署项目,打开浏览器访问url: http://localhost:8080/cookieshandling/getcookies.jsp ,应该会看到结果如下 -
使用jsp删除cookie
删除cookies非常简单。如果想要删除一个cookie,那么只需要按照这三个步骤 -
- 读取已存在的cookie并将其存储在cookie对象中。
- 使用setmaxage()方法将cookie的过期时间设置为零,以删除现有的cookie。
- 将此cookie添加回响应头。
以下示例将显示如何删除名为username的现有cookie,并且下次运行访问getcookies.jsp时,将不再返回username的cookies值。
文件:deletecookies.jsp -
<%@ page language="java" contenttype="text/html; charset=utf-8"
pageencoding="utf-8"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>删除cookies</title>
</head>
<body>
<div style="margin: auto; width: 80%;">
<center>
<h1>删除cookies</h1>
</center>
<%
cookie cookie = null;
cookie[] cookies = null;
// get an array of cookies associated with the this domain
cookies = request.getcookies();
if( cookies != null ) {
out.println("<h2>找到的cookie名称和值</h2>");
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
if(cookie.getname().equals("username")) {
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>");
}
%>
</div>
</body>
</html> 重新部署项目,打开浏览器访问url: http://localhost:8080/cookieshandling/deletecookies.jsp ,应该会看到结果如下 -
现在再次运行:getcookies.jsp,它应该只显示一个cookie,如下所示:
也可以手动删除浏览器中的cookie。从工具菜单开始,选择internet选项。要删除所有cookie,请单击删除cookie按钮。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!