1 10 11 package org.jivesoftware.util; 12 13 import javax.servlet.http.Cookie ; 14 import javax.servlet.http.HttpServletRequest ; 15 import javax.servlet.http.HttpServletResponse ; 16 17 public class CookieUtils { 18 19 30 public static Cookie getCookie(HttpServletRequest request, String name) { 31 Cookie cookies[] = request.getCookies(); 32 if (cookies == null || name == null || name.length() == 0) { 34 return null; 35 } 36 Cookie cookie = null; 38 for (int i = 0; i < cookies.length; i++) { 39 if (cookies[i].getName().equals(name)) { 42 cookie = cookies[i]; 43 if (request.getServerName().equals(cookie.getDomain())) { 47 break; 48 } 49 } 50 } 51 return cookie; 52 } 53 54 61 public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, 62 Cookie cookie) 63 { 64 if (cookie != null) { 65 String path = request.getContextPath() == null ? "/" : request.getContextPath(); 67 if ("".equals(path)) { 68 path = "/"; 69 } 70 cookie.setPath(path); 71 cookie.setValue(""); 72 cookie.setMaxAge(0); 73 response.addCookie(cookie); 74 } 75 } 76 77 86 public static void setCookie(HttpServletRequest request, HttpServletResponse response, 87 String name, String value) 88 { 89 setCookie(request, response, name, value, 60*60*24*30); 91 } 92 93 104 public static void setCookie(HttpServletRequest request, HttpServletResponse response, 105 String name, String value, int maxAge) 106 { 107 if (value == null) { 110 value = ""; 111 } 112 String path = request.getContextPath() == null ? "/" : request.getContextPath(); 113 if ("".equals(path)) { 114 path = "/"; 115 } 116 Cookie cookie = new Cookie (name, value); 117 cookie.setMaxAge(maxAge); 118 cookie.setPath(path); 119 response.addCookie(cookie); 120 } 121 } 122 | Popular Tags |