1.设置Cookie
Cookie cookie = new Cookie("key", "value");
cookie.setMaxAge(60);
设置60秒生存期,如果设置为负值的话,则为浏览器进程Cookie(内存中保存),关闭浏览器就失效。
cookie.setPath("/test/test2");
设置Cookie路径,不设置的话为当前路径(对于Servlet来说为request.getContextPath() + web.xml里配置的该Servlet的url-pattern路径部分)
response.addCookie(cookie);
2.读取Cookie
该方法可以读取当前路径以及“直接父路径”的所有Cookie对象,如果没有任何Cookie的话,则返回null
Cookie[] cookies = request.getCookies();
3.删除Cookie
Cookie cookie = new Cookie("key", null);
cookie.setMaxAge(0);
设置为0为立即删除该Cookie
cookie.setPath("/test/test2");
删除指定路径上的Cookie,不设置该路径,默认为删除当前路径Cookie
response.addCookie(cookie);
4.修改Cookie
Cookie[] cookies=request.getCookies();
if(cookies.length>1){
for(int i=0;i<cookies.length;i++){
if(cookies[i].getName().equals("key")) {
String oldValue = cookies[i].getValue();
String newValue= "newValue";
cookies[i].setValue(newValue);
response.addCookie(cookies[i]);
break;
}
}
}
===============================================================
1.实现两个网站www.wangwz.com和post.wangwz.com共用Cookies
2.添加Cookies
Cookie cookie = new Cookie("name", "wangwz");
cookie.setPath("/");//这个要设置
cookie.setDomain(".wangwz.com");//这个也要设置才能实现上面的两个网站共用
cookie.setMaxAge(365*24*60*60);//不设置的话,则cookies不写入硬盘,而是写在内存,只在当前页面有用,以秒为单位
response.addCookie(cookie);
cookie = new Cookie("nick", URLEncoder.encode("王伟宗","UTF-8"));
cookie.setPath("/");
cookie.setDomain(".wangwz.com");
cookie.setMaxAge(365*24*60*60);
response.addCookie(cookie);
3.获取cookies
Cookie cookies[] = request.getCookies();
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
if (cookies[i].getName().equals("nick"))
{
System.out.println(URLDecoder.decode(cookies[i].getValue(),"UTF-8"));
}
}
}
4.删除cookies
Cookie cookies[] = request.getCookies();
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
if (cookies[i].getName().equals("nick"))
{
Cookie cookie = new Cookie("nick","");//这边得用"",不能用null
cookie.setPath("/");//设置成跟写入cookies一样的
cookie.setDomain(".wangwz.com");//设置成跟写入cookies一样的
response.addCookie(cookie);
}
}
}
========================================================
========================================================
应用实例
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.util.*" errorPage="" %>
<%@ page import="java.net.URLDecoder" %> //注意导入此包
<%
Cookie cookie=new Cookie("hi","welcome");
response.addCookie(cookie);
Cookie[] cookies=request.getCookies();
if(cookies!=null){
for(int i=0;i<cookies.length;i++){
if(cookies[i].getName().equals("hi")){
String cookieValue=URLDecoder.decode(cookies[i].getValue(),"utf-8");
out.print("hi="+cookieValue);
}
}
}else{
out.print(" no cookie");
}
%>