Skip to content

Instantly share code, notes, and snippets.

@magicianlib
Last active June 12, 2022 12:25
Show Gist options
  • Save magicianlib/ade2f485a0f506c0312381a231a72e2c to your computer and use it in GitHub Desktop.
Save magicianlib/ade2f485a0f506c0312381a231a72e2c to your computer and use it in GitHub Desktop.
public final class CookieUtils {
public static Cookie getCookie(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
int len = cookies.length;
for (int index = 0; index < len; ++index) {
Cookie cookie = cookies[index];
if (cookie.getName().equals(name)) {
return cookie;
}
}
}
return null;
}
public static void addCookie(HttpServletResponse response, String domain, String path, String name, String value) {
addCookie(response, domain, path, name, value, -1);
}
public static void addCookie(HttpServletResponse response, String domain, String path, String name, String value, int maxAge) {
String colon = ":";
Cookie cookie = new Cookie(name, value);
if (domain.contains(colon)) {
domain = domain.split(colon)[0];
}
cookie.setDomain(domain);
cookie.setPath(path);
cookie.setMaxAge(maxAge);
response.addCookie(cookie);
}
public static void removeCookie(HttpServletResponse response, String domain, String path, String name) {
addCookie(response, domain, path, name, null, 0);
}
private CookieUtils() {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment