1 16 17 package org.springframework.web.util; 18 19 import javax.servlet.http.Cookie ; 20 import javax.servlet.http.HttpServletResponse ; 21 22 import org.apache.commons.logging.Log; 23 import org.apache.commons.logging.LogFactory; 24 25 40 public class CookieGenerator { 41 42 45 public static final String DEFAULT_COOKIE_PATH = "/"; 46 47 50 public static final int DEFAULT_COOKIE_MAX_AGE = Integer.MAX_VALUE; 51 52 53 protected final Log logger = LogFactory.getLog(getClass()); 54 55 private String cookieName; 56 57 private String cookieDomain; 58 59 private String cookiePath = DEFAULT_COOKIE_PATH; 60 61 private int cookieMaxAge = DEFAULT_COOKIE_MAX_AGE; 62 63 private boolean cookieSecure = false; 64 65 66 69 public void setCookieName(String cookieName) { 70 this.cookieName = cookieName; 71 } 72 73 76 public String getCookieName() { 77 return cookieName; 78 } 79 80 84 public void setCookieDomain(String cookieDomain) { 85 this.cookieDomain = cookieDomain; 86 } 87 88 91 public String getCookieDomain() { 92 return cookieDomain; 93 } 94 95 99 public void setCookiePath(String cookiePath) { 100 this.cookiePath = cookiePath; 101 } 102 103 106 public String getCookiePath() { 107 return cookiePath; 108 } 109 110 114 public void setCookieMaxAge(int cookieMaxAge) { 115 this.cookieMaxAge = cookieMaxAge; 116 } 117 118 121 public int getCookieMaxAge() { 122 return cookieMaxAge; 123 } 124 125 130 public void setCookieSecure(boolean cookieSecure) { 131 this.cookieSecure = cookieSecure; 132 } 133 134 138 public boolean isCookieSecure() { 139 return cookieSecure; 140 } 141 142 143 155 public void addCookie(HttpServletResponse response, String cookieValue) { 156 Cookie cookie = createCookie(cookieValue); 157 cookie.setMaxAge(getCookieMaxAge()); 158 if (isCookieSecure()) { 159 cookie.setSecure(true); 160 } 161 response.addCookie(cookie); 162 if (logger.isDebugEnabled()) { 163 logger.debug("Added cookie with name [" + getCookieName() + "] and value [" + cookieValue + "]"); 164 } 165 } 166 167 177 public void removeCookie(HttpServletResponse response) { 178 Cookie cookie = createCookie(""); 179 cookie.setMaxAge(0); 180 response.addCookie(cookie); 181 if (logger.isDebugEnabled()) { 182 logger.debug("Removed cookie with name [" + getCookieName() + "]"); 183 } 184 } 185 186 195 protected Cookie createCookie(String cookieValue) { 196 Cookie cookie = new Cookie (getCookieName(), cookieValue); 197 if (getCookieDomain() != null) { 198 cookie.setDomain(getCookieDomain()); 199 } 200 cookie.setPath(getCookiePath()); 201 return cookie; 202 } 203 204 } 205 | Popular Tags |