建立一个无生命周期的cookie,即随着浏览器的关闭即消失的cookie,代码如下
HttpServletRequest request HttpServletResponse response Cookie cookie = new Cookie("cookiename","cookievalue"); response.addCookie(cookie);
下面建立一个有生命周期的cookie,可以设置他的生命周期
cookie = new Cookie("cookiename","cookievalue"); cookie.setMaxAge(3600); //设置路径,这个路径即该工程下都可以访问该cookie 如果不设置路径,那么只有设置该cookie路径及其子路径可以访问 cookie.setPath("/"); response.addCookie(cookie);
下面介绍如何读取cookie,读取cookie代码如下
Cookie[] cookies = request.getCookies();//这样便可以获取一个cookie数组 for(Cookie cookie : cookies){ cookie.getName();// get the cookie name cookie.getValue(); // get the cookie value }
上面就是基本的读写cookie的操作。我们在实际中最好进行一下封装,比如增加一个cookie,我们关注的是cookie的name,value,生命周期,所以进行封装一个函数,代码如下
package cn.form1.utils; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** 封装Cookie方法类 / public class CookieUtil { /* 设置cookie @param response @param name cookie名字 @param value cookie值 @param maxAge cookie生命周期 以秒为单位 / public static void addCookie(HttpServletResponse response, String name, String value, int maxAge){ Cookie cookie = new Cookie(name,value); //设置路径,这个路径即该工程下都可以访问该cookie 如果不设置路径,那么只有设置该cookie路径及其子路径可以访问 cookie.setPath("/"); if(maxAge>0) cookie.setMaxAge(maxAge); response.addCookie(cookie); } /* 根据名字获取cookie @param request @param name cookie名字 @return / public static Cookie getCookieByName(HttpServletRequest request,String name){ Map<String,Cookie> cookieMap = ReadCookieMap(request); if(cookieMap.containsKey(name)){ Cookie cookie = (Cookie)cookieMap.get(name); return cookie; }else{ return null; } } /* 删除已知名称的cookie @param response @param name cookie名字 / public static void delCookie(HttpServletResponse response, String name){ Cookie cookie = new Cookie(name,null); cookie.setPath("/"); cookie.setMaxAge(0); response.addCookie(cookie); } /* 删除所有cookie @param response @param request / public static void delCookieAll(HttpServletResponse response, HttpServletRequest request){ Cookie[] cookies=request.getCookies(); for(Cookie cookie: cookies){ cookie.setMaxAge(0); cookie.setPath("/"); response.addCookie(cookie); } } /* 将cookie封装到Map里面 @param request @return / private static Map<String,Cookie> ReadCookieMap(HttpServletRequest request){ Map<String,Cookie> cookieMap = new HashMap<String,Cookie>(); Cookie[] cookies = request.getCookies(); if(null!=cookies){ for(Cookie cookie : cookies){ cookieMap.put(cookie.getName(), cookie); } } return cookieMap; } }