保存信息到cookie中

2017-06-12 18:27:00    admin    1105    原创
摘要:保存信息到cookie中

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class WebUtils {
/**设置Cookie值*/
public static void setCookie(HttpServletResponse response, String key, String value, int days, String domain) {
if ((key != null) && (value != null)) {
Cookie cookie = new Cookie(key, value);
cookie.setMaxAge(days * 24 * 60 * 60);
cookie.setPath("/");
if (org.apache.commons.lang.StringUtils.isNotEmpty(domain)) {
cookie.setDomain(domain);
}
response.addCookie(cookie);
}
}
/**获取Cookie值*/
public static String getCookie(HttpServletRequest request, String key) {
Cookie[] cookies = request.getCookies();
String resValue = "";
if ((cookies != null) && (cookies.length > 0)) {
for (int i = 0; i < cookies.length; i++) {
if ((!key.equalsIgnoreCase(cookies[i].getName()))
|| (!org.apache.commons.lang.StringUtils
.isNotEmpty(cookies[i].getValue())))
continue;
resValue = cookies[i].getValue();
}

}
return resValue;
}

/**删除默认域名下的*/
public static void deleteCookie(HttpServletRequest request,
HttpServletResponse response, String name) {
deleteCookieDomain(request, response, name, MYDOMAIN);
}

/**删除某域下的Cookie*/
public static void deleteCookieDomain(HttpServletRequest request,
HttpServletResponse response, String name, String domain) {
Cookie[] cookies = request.getCookies();
if ((cookies != null) && (cookies.length > 0))
for (int i = 0; i < cookies.length; i++) {
if (!name.equalsIgnoreCase(cookies[i].getName()))
continue;
Cookie ck = new Cookie(cookies[i].getName(), null);
ck.setPath("/");
if (org.apache.commons.lang.StringUtils.isNotEmpty(domain)) {
ck.setDomain(domain);
}
ck.setMaxAge(0);
response.addCookie(ck);
return;
}
}
}


豫ICP备15006410号
蝉知 蝉知4.5.2