js方式
//读取cookies
function getCookieValue(name){var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
}
//除去cookie
function removeCookie(name){
var date = new Date();
date.setTime(date.getTime() - 10000);
document.cookie = name + "=a; expires=" + date.toGMTString();
}
//添加cookie
function setCookieValue(name,value){
var Days = 365; //此 cookie 将被保存 30 天
var exp = new Date(); //new Date("December 31, 9998");
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
document.cookie = name + "=" + escape(value) + ";expires="
+ exp.toGMTString();
}
java方式
//设置cookie
Cookie cookie = new Cookie(name,value);
cookie.setPath("/"); //注意如果没有该条语句,则只能在设置cookie的路径下访问,加上此条语句表示工程下所有的路径都能访问该cookie
response.addCookie(cookie);
//注意如果value是中文需要转义以下
value=URLEncoder.encode(value, "UTF-8");
//读取cookie
Cookie[] cookie = request.getCookies();for (int i = 0; i < cookie.length; i++) {
Cookie cook = cookie[i];
if(cook.getName().equalsIgnoreCase("shopName")){ //获取键
try {
shopName=URLDecoder.decode(cook.getValue().toString(),"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//删除cookie
一、删除已知名称的Cookie(方案:重新建立同名立即删除类型的Cookie)
1)第一种方式
Cookie newCookie=new Cookie(“username”,null); //假如要删除名称为username的Cookie
newCookie.setMaxAge(0); //立即删除型
newCookie.setPath(“/”); //项目所有目录均有效,这句很关键,否则不敢保证删除
response.addCookie(newCookie); //重新写入,将覆盖之前的
2)第二种方式
//获取cookie中存储的店铺名
Cookie[] cookie = request.getCookies();
for (int i = 0; i < cookie.length; i++) {
Cookie cook = cookie[i];
if(cook.getName().equalsIgnoreCase(name)){ //获取键
cook.setMaxAge(-1);
}
}
二、删除所有Cookie
Cookie[] cookies=request.getCookies();
for(Cookie cookie: cookies){
cookie.setMaxAge(0);
cookie.setPath(“/”);
response.addCookie(cookie);
}