Cookie是一种发送到客户浏览器的文本串句柄,并保存在客户机硬盘上,可以用来在某个Web站点会话之间持久地保持数据。Request和Response对象都有一组Cookie。Request.cookie集合是一系列Cookie,从客户端与HTTP Request一起发送到Web服务器。反过来,如果你希望把Cookie发送到客户机,就可以使用Response.Cookies.
1、Expires属性
该属性可以赋一个日期,过了这个日期Cookie就不能再被使用了。通过给Expires属性赋一个过期的日期,就可以删除Cookie。如:
<%Response.cookies("passtime").Expires=DateAdd("m", 1, NOW)%>
这样设置Cookie在一个月后过期。
2、Domain属性
该属性定义Cookie要传送的唯一域。如:Cookie只传送给Microsoft的人,则可以使用以下代码。
<%Response.Cookies("domain").Domain="http://www.microsoft.com/"%>
经常的cookie只能在一个应用中共享,即一个cookie只能由创建它的应用获得。
1.在同一应用服务器内共享的方法:设置cookie.setPath("/");
设本机tomcat/webapp下面有两个应用:cas和webapp_b
1).原来在cas下面设置的cookie,在webapp_b下面获取不到,path默认是产生cookie的应用的路径。
2).若在cas下面设置cookie的时候,增加一条: cookie.setPath("/");或者cookie.setPath("/webapp_b/"); 就可以在webapp_b下面获取 到cas设置的cookie了。
3).此处的参数,是相对于应用服务器存放应用的文件夹的根目录而言的(比如tomcat下面的webapp),因此cookie.setPath("/");之后,可以在webapp文件夹下的所有应用共享cookie,而cookie.setPath("/webapp_b/"),是指cas应用设置的cookie只能在webapp_b应用下的获得,即便是产生这个cookie的cas应用也不可以。
4).设置cookie.setPath("/webapp_b/jsp/")的时候,只有在webapp_b/jsp下面可以获得cookie,在webapp_b下面但是在jsp文件夹外的都不能获得cookie。
5).设置cookie.setPath("/webapp_b/"),是指在webapp_b下面才可以使用cookie,这样就不可以在产生cookie的应用cas下面获取cookie了。
6).有多条cookie.setPath("XXX");语句的时候,起作用的以最后一条为准。
2.跨域共享cookie的方法:设置cookie.setDomain(".jszx.com");
A机所在的域:home.langchao.com,A有应用cas
B机所在的域:jszx.com,B有应用webapp_b
1)在cas下面设置cookie的时候,增加cookie.setDomain(".jszx.com");,这样在webapp_b下面就可以取到cookie。
2)这个参数必须以“.”开始。
3)输入url访问webapp_b的时候,必须输入域名才能解析。比如说在A机器输入:http://lc-bsp.jszx.com:8080/webapp_b,可以获取cas在客户端设置的cookie,而B机器访问本机的应用,输入:http://localhost:8080/webapp_b则不可以获得cookie。
4)设置了cookie.setDomain(".jszx.com");,还可以在默认的home.langchao.com下面共享。
3.使用cookie实现保存用户和密码的功能实例
使用struts2框架:
User.java:
package com.neusoft.struts.lianxi0409; public class User { private String username; private String password; private String jilu; public String getJilu() { return jilu; } public void setJilu(String jilu) { this.jilu = jilu; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
ActionAttribute.java:
package com.neusoft.struts.lianxi0409;
import java.util.Map;
import javax.servlet.http.Cookie;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
public class ActionAttribute extends ActionSupport implements SessionAware{
private Map<String, Object> session;
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public void setSession(Map<String, Object> session) {
// TODO Auto-generated method stub
this.session = session;
}
public String execute() {
session.put("user", user.getUsername());
if (session != null) {
if (user != null && user.getUsername().equals("qqq") && user.getPassword().equals("qqq")) {
Cookie usernamecookie = new Cookie("username", user.getUsername());
Cookie passwordcookie = new Cookie("password", user.getPassword());
// 设置保存周期
usernamecookie.setMaxAge(60 * 5);
passwordcookie.setMaxAge(60 * 5);
// 设置cookie共享范围
usernamecookie.setPath("/struts2_actionattribute_lianxi0409");
passwordcookie.setPath("/struts2_actionattribute_lianxi0409");
ServletActionContext.getResponse().addCookie(usernamecookie);
ServletActionContext.getResponse().addCookie(passwordcookie);
return SUCCESS;
} else {
return "login";
}
} else {
return "login";
}
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8" ?> - <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> - <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> - <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> - <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app>
struts.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <constant name="struts.i18n.encoding" value="utf-8" /> <package name="attribute" namespace="/attribute" extends="struts-default"> <action name="attribute" class="com.neusoft.struts.lianxi0409.ActionAttribute"> <result name="success">/index.jsp</result> <result name="login">/login.jsp</result> </action> </package> </struts>
login.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
String username = "";
String password = "";
response.setContentType("text/html;charset=gbk");
Cookie[] cookie = request.getCookies();
if (cookie != null) {
for (int i = 0; i < cookie.length; i++) {
if (cookie[i].getName().equals("username")) {
username = cookie[i].getValue();
} else if (cookie[i].getName().equals("password")) {
password = cookie[i].getValue();
break;
}
}
}
%>
<form action="attribute/attribute" method="post">
<table border="1">
<tr>
<td>用户名</td>
<td><input type="text" name="user.username" value="<%=username%>"></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="user.password" value="<%=password%>"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交">
<input type="reset" value="重设">
</td>
</tr>
</table>
</form>
</body>
</html>
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <%@taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <s:property value="#session.user"/>你好 <s:debug></s:debug> </body> </html>
用户第一次登陆后,第二次在保存有效时间内就不用再输入用户名和密码了!