Cookie工具类,提供Cookie的创建、获取、删除方法。
源码如下:(点击下载 - )
1 import javax.servlet.http.Cookie; 2 import javax.servlet.http.HttpServletRequest; 3 import javax.servlet.http.HttpServletResponse; 4 5 /** 6 * Cookie工具类 7 * 8 */ 9 public class CookieUtil {10 11 private CookieUtil() {12 }13 14 /**15 * 添加cookie16 * 17 * @param response18 * @param name19 * @param value20 * @param maxAge21 */22 public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {23 Cookie cookie = new Cookie(name, value);24 cookie.setPath("/");25 if (maxAge > 0) {26 cookie.setMaxAge(maxAge);27 }28 response.addCookie(cookie);29 }30 31 /**32 * 删除cookie33 * 34 * @param response35 * @param name36 */37 public static void removeCookie(HttpServletResponse response, String name) {38 Cookie uid = new Cookie(name, null);39 uid.setPath("/");40 uid.setMaxAge(0);41 response.addCookie(uid);42 }43 44 /**45 * 获取cookie值46 * 47 * @param request48 * @return49 */50 public static String getUid(HttpServletRequest request,String cookieName) {51 Cookie cookies[] = request.getCookies();52 for (Cookie cookie : cookies) {53 if (cookie.getName().equals(cookieName)) {54 return cookie.getValue();55 }56 }57 return null;58 }59 }