1.实现两个网站和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);
}
}
}
注:在网上看到删除是这样做的cookies[i].setMaxAge(0);但我试过,好像不能删除掉cookies
阅读(1332) | 评论(0) | 转发(0) |