谈世赞 2014-12-26
SSH中的重构 cookies的管理
目的:集中管理cookies
做法:建造一个类单独管理cookies
下面是一个简单的例子保存用户名(两个星期的时效)
public class CookieInfo { public static final String USERNAME = "USERNAME"; public static final int TWOWEEK = 60 * 60 * 24 * 30; public static String getUserName(HttpServletRequest request) { return getCookie(request, USERNAME); } public static void addUserName(HttpServletResponse response, String value) { addCookie(response, USERNAME, value); } public static void delUserName(HttpServletRequest request, HttpServletResponse response) { delCookie(request,response,USERNAME); } private static void addCookie(HttpServletResponse response, String key, String value) { Cookie cookie = new Cookie(key, java.net.URLEncoder.encode(value)); cookie.setMaxAge(TWOWEEK); response.addCookie(cookie); } private static String getCookie(HttpServletRequest request, String key) { if (request.getCookies() == null) return ""; for (Cookie cookie : request.getCookies()) { if (key.equals(cookie.getName())) { return java.net.URLDecoder.decode(cookie.getValue()); } } return ""; } private static void delCookie(HttpServletRequest request,HttpServletResponse response,String key) { if (request.getCookies() == null) return; for (Cookie cookie : request.getCookies()) { if (key.equals(cookie.getName())) { cookie.setMaxAge(0); response.addCookie(cookie); } } } }