1 package de.juplo.yourshouter;
4 import javax.servlet.http.Cookie;
5 import javax.servlet.http.HttpServletRequest;
6 import javax.servlet.http.HttpServletResponse;
7 import org.slf4j.Logger;
8 import org.slf4j.LoggerFactory;
10 import org.springframework.web.util.CookieGenerator;
11 import org.thymeleaf.util.StringUtils;
15 * Utility class for managing the cookie that remembers the user.
19 final class UserCookieGenerator
21 private final static Logger LOG =
22 LoggerFactory.getLogger(UserCookieGenerator.class);
24 public final static UserCookieGenerator INSTANCE = new UserCookieGenerator();
27 private final CookieGenerator generator = new CookieGenerator();
31 * Constructs an instance of this class, using <code>user</code> as the
34 private UserCookieGenerator()
36 generator.setCookieName("user");
41 * Creates a cookie with the name <code>user</code>, that stores the ID of
42 * the user for subsequent calls.
45 * The ID of the current user
47 * The {@link HttpServletResponse} to store the cookie in.
49 public void addCookie(String user, HttpServletResponse response)
51 LOG.debug("adding cookie {}={}", generator.getCookieName(), user);
52 generator.addCookie(response, user);
56 * Removes the cookie with the name <code>user</code> by storing an empty
57 * string as its value.
60 * The {@link HttpServletResponse} to remove the cookie from.
62 public void removeCookie(HttpServletResponse response)
64 LOG.debug("removing cookie {}", generator.getCookieName());
65 generator.addCookie(response, "");
69 * Reads the current value of the cookie with the name <code>user</code>.
72 * The {@link HttpServletRequest} to read the cookie-value from.
74 * The value of the cookie with the name <code>user</code>, or
75 * <code>null</code>, if no cookie by that name can be found or the value
76 * of the cookie is an empty string.
78 public String readCookieValue(HttpServletRequest request)
80 String name = generator.getCookieName();
81 Cookie[] cookies = request.getCookies();
84 for (Cookie cookie : cookies)
86 if (cookie.getName().equals(name))
88 String value = cookie.getValue();
89 if (!StringUtils.isEmptyOrWhitespace(value))
91 LOG.debug("found cookie {}={}", name, value);
97 LOG.debug("cookie \"{}\" not found!", name);