📄 cookieutils.java
字号:
package org.whatisjava.dang.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;
public class CookieUtils {
public static final int MAX_AGE = 60 * 60 * 24 * 7;
public static final String USER_ID = "dangdang.user.id";
public static final String USER_TEMP_ID = "dangdang.user.temp.id";
public static final String CART_ID = "dangdang.cart.id";
/**
*
* @param response
* @param key
* @param value
* @throws UnsupportedEncodingException
*/
public static void addCookie(HttpServletResponse response, String key,
String value) throws UnsupportedEncodingException {
addCookie(response, key, value, MAX_AGE);
}
public static void deleteCookie(HttpServletResponse response, String key) {
Cookie cookie = new Cookie(key, "");
cookie.setMaxAge(0);
cookie.setPath("/dang");
response.addCookie(cookie);
}
/**
*
* @param response
* @param key
* @param value
* @param maxAge
* @throws UnsupportedEncodingException
*/
public static void addCookie(HttpServletResponse response, String key,
String value, int maxAge) throws UnsupportedEncodingException {
value = URLEncoder.encode(value, "utf-8");
Cookie cookie = new Cookie(key, value);
cookie.setMaxAge(maxAge);
cookie.setPath("/dang");
response.addCookie(cookie);
}
/**
*
* @param request
* @param key
* @return
* @throws UnsupportedEncodingException
*/
public static String findCookie(HttpServletRequest request, String key)
throws UnsupportedEncodingException {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (key.equals(cookies[i].getName())) {
System.out.println("cookie:" + cookies[i].getName() + "="
+ cookies[i].getValue());
return URLDecoder.decode(cookies[i].getValue(), "utf-8");
}
}
}
return null;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -