packagecom.test;importorg.apache.commons.lang.StringUtils;importorg.springframework.util.Assert;importjavax.servlet.http.Cookie;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;/*** Cookie 辅助类*/
public classCookieUtils {/*** 根据cookie名称获得cookie
*@paramrequest
*@paramname cookie的名称
*@return
*/
public staticCookie getCookie(HttpServletRequest request, String name) {
Assert.notNull(request);
Cookie[] cookies=request.getCookies();if (cookies != null && cookies.length > 0) {for(Cookie c : cookies) {if(c.getName().equals(name)) {returnc;
}
}
}return null;
}/*** 保存cookie 保存在根目录下
*@paramrequest
*@paramresponse
*@paramname cookie名称
*@paramvalue cookie的值
*@paramexpiry 过期时间(可以为空)
*@paramdomain 域名(可以为空)
*@return
*/
public staticCookie addCookie(HttpServletRequest request,
HttpServletResponse response, String name, String value,
Integer expiry, String domain) {
Cookie cookie= newCookie(name, value);if (expiry != null) {
cookie.setMaxAge(expiry);
}if(StringUtils.isNotBlank(domain)) {
cookie.setDomain(domain);
}
String ctx=request.getContextPath();
cookie.setPath(StringUtils.isBlank(ctx)? "/": ctx);
response.addCookie(cookie);returncookie;
}/*** 清除cookie
*@paramrequest
*@paramresponse
*@paramname cookie名称
*@paramdomain*/
public static voidcancleCookie(HttpServletRequest request,
HttpServletResponse response, String name, String domain) {
Cookie cookie= new Cookie(name, "");
cookie.setMaxAge(0);
String ctx=request.getContextPath();
cookie.setPath(StringUtils.isBlank(ctx)? "/": ctx);if(StringUtils.isNotBlank(domain)) {
cookie.setDomain(domain);
}
response.addCookie(cookie);
}
}