servlet操作cookie工具类
最近封装了一个Cookie的工具类,挺好用的。
package com.zhengshuiguang.blog; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CookieUtils { private static int cookieMaxAge = 7 * 24 * 3600; private static String path = "/"; private static String domain; /** * 根据Cookie名称得到Cookie对象,不存在该对象则返回null * * @param request * @param name * @return */ public static Cookie getCookie(HttpServletRequest request, String name) { Cookie[] cookies = request.getCookies(); if ((null == cookies) || (null == name) || (name.length() == 0)) { return null; } Cookie cookie = null; for (Cookie c : cookies) { if (name.equals(c.getName())) { cookie = c; break; } } return cookie; } /** * 添加一条新的Cookie,默认7天过期时间(单位:秒) * * @param response * @param name * @param value */ public static void setCookie(HttpServletResponse response, String name, String value) { setCookie(response, name, value, cookieMaxAge); } /** * 添加一条新的Cookie,可以指定过期时间(单位:秒) * * @param response * @param name * @param value * @param maxValue */ public static void setCookie(HttpServletResponse response, String name, String value, int maxValue) { if (null == name) { return; } if (null == value) { value = ""; } Cookie cookie; try { cookie = new Cookie(name, URLEncoder.encode(value, "UTF-8")); cookie.setPath(path); if(domain != null) { cookie.setDomain(domain); } if (maxValue != 0) { cookie.setMaxAge(maxValue); } else { cookie.setMaxAge(cookieMaxAge); } response.addCookie(cookie); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } /** * 移出指定名称的cookie * @param request * @param response * @param name */ public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String name) { if (null == name) { return; } Cookie cookie = getCookie(request, name); if (null != cookie) { cookie.setPath(path); if(domain != null) { cookie.setDomain(domain); } cookie.setValue(""); cookie.setMaxAge(0); response.addCookie(cookie); } } //============get/set=============== public static int getCookieMaxAge() { return cookieMaxAge; } public static void setCookieMaxAge(int num) { cookieMaxAge = num; } public static String getPath() { return path; } public static void setPath(String string) { path = string; } public static String getDomain() { return domain; } public static void setDomain(String string) { domain = string; } }
用法和javax.servlet.http.Cookie基本一致,只不过是默认的cookie保存时间为7天(不传入时间参数的情况下),如果想让cookie在关闭浏览器后消失,可以在调用setCookie时传入最后一个负数作为时间参数。
文章网址:http://blog.zhengshuiguang.com/java/javaCookie.html
随意转载^^但请附上教程地址。
评论已关闭