在写一个 记住用户名的功能 用到了些cookie的功能 顺便写了一个工具类 想了想 还是贴出来 要是有朋友 用到 也就方便了
public class CookieUtil {
/**
* @param key
* 主键
* @param value
* 值
* @param maxAge
* 有效时间
* @param response
* 响应
* @return void
*/
public void writeCookie(String key, String value, int maxAge,
HttpServletResponse response) {
Cookie namecookie = new Cookie(key, value);
namecookie.setMaxAge(maxAge);
response.addCookie(namecookie);
}
/**
* @param key
* 主键
* @param value
* 值
* @param maxAge
* 有效时间
* @return void
*/
public void writeCookie(String key, String value,
HttpServletResponse response) {
Cookie namecookie = new Cookie(key, value);
namecookie.setMaxAge(60 * 60 * 24 * 365);
response.addCookie(namecookie);
}
/**
* @param request
* 请求
* @param key
* 主键
* @return String 读取key 对应的值
*/
public String readCookie(String key, HttpServletRequest request) {
String value = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
Cookie c = cookies[i];
if (c.getName().equalsIgnoreCase(key)) {
value = c.getValue();
return value;
}
}
}
return value;
}
}