CookieUtil
整理于课堂笔记
package util;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Cookie工具类,提供了添加cookie、 读取cookie、删除cookie的方法。
*
*/
public class CookieUtil {
/**
* 添加cookie的方法
*/
public static void addCookie(String name, String value, int age, String path, HttpServletResponse response)
throws UnsupportedEncodingException {
/*
* cookie只能保存合法的ascii字符, 建议,在添加cookie时,最好使用 URLEncoder.encode方法进行统一的 编码处理。
*/
Cookie c = new Cookie(name, URLEncoder.encode(value, "utf-8"));
// 设置cookie的生存时间
c.setMaxAge(age);
// 设置cookie的路径
c.setPath(path);
response.addCookie(c);
}
/**
* 依据cookie名读取对应的cookie的值, 如果找不到,返回null。
*/
public static String findCookie(String name, HttpServletRequest request) throws UnsupportedEncodingException {
String value = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
String name1 = c.getName();
if (name1.equals(name)) {
value = URLDecoder.decode(c.getValue(), "utf-8");
}
}
}
return value;
}
/**
* 删除某个cookie
*/
public static void deleteCookie(String name, String path, HttpServletResponse response) {
Cookie c = new Cookie(name, "");
c.setMaxAge(0);
c.setPath(path);
response.addCookie(c);
}
}