通过简单封装实现Cookie的存取
一般我们通过HttpServletRequest对象和HttpServletResponse对象实现对Cookie的存和取,因为Cookie的没有提供直接取Cookie的方法,所以进行一个简单封装.
public class CookieUtil {
/**
* 编辑工具API方法,通过cookie的名称,获取cookie的值
*/
public static String getCookieValue(HttpServletRequest request,String cookieName) {
Cookie[] cookies = request.getCookies();
if(cookies == null || cookies.length==0) {
//如果没有cookie,则直接返回null
return null;
}
String value = null;
for (Cookie cookie : cookies) {
if(cookie.getName().equals(cookieName)) {
value = cookie.getValue();
break;
}
}
return value;
}
//向浏览器发送Cookie
public static void addCookie(
HttpServletRequest request,
HttpServletResponse response,
String cookieName,
String cookieVlaue,
int seconds,
String domain) {
Cookie cookie =
new Cookie(cookieName, cookieVlaue);
cookie.setMaxAge(seconds);
cookie.setPath("/");
cookie.setDomain(domain);
response.addCookie(cookie);
}
}