Spring Boot Cookies Example
In this article, we’ll explore how to use cookies in the Spring Boot application. A cookie is a small piece of information stored in the user’s web browser. Cookies are helpful to show user personalized contents, login management, etc.
In a Spring Boot application, a cookie can be set by using the Cookie
class and add in server response using HttpServletResponse
class, similarly, a cookie can be retrieved by using @CookieValue
annotation.
In this example, we’ll learn the following about a cookie:
- Set a cookie
- Get the cookie
- Set expiry of a cookie
- Delete a cookie
1. Set Cookie
addCookie(Cookie cookie)
method of HttpServletResponse
class is used to set a new cookie with a Cookie
class instance.
@GetMapping("/set")
public String setCookie(HttpServletResponse response) {
// set a new cookie
Cookie cookie = new Cookie("color", "blue");
// add cookie in server response
response.addCookie(cookie);
return "Spring Boot Cookies";
}
2. Get Cookie
The @CookieValue
annotation is the easiest way to get a cookie from the user request. It will throw the MissingRequestCookieException
when the requested cookie is not found. It is handled by setting a default value of a requested cookie.
@GetMapping("/get")
public String getCookie(@CookieValue(value = "color",
defaultValue = "No color found in cookie") String color) {
return "Sky is: " + color;
}
3. Set Cookie Expiry
Cookie expiry is the time period in which it is removed from the web browser. Cookie expiry is set by the setMaxAge(int expiry)
method where expiry
is an integer specifying the maximum age of the cookie in seconds; if negative, means the cookie is not stored; if zero, deletes the cookie.
@GetMapping("/expiry")
public String setCookieExpiry(HttpServletResponse response) {
int cookieAgeInSeconds = 86400;
Cookie cookie = new Cookie("website", "https://websparrow.org");
cookie.setMaxAge(cookieAgeInSeconds); // expire in 1 day
response.addCookie(cookie);
return "Cookie will expire in " + cookieAgeInSeconds + "seconds.";
}
4. Delete Cookie
To delete a cookie, set the Max-Age
directive to 0
and unset its value.
@GetMapping("/delete")
public String deleteCookie(HttpServletResponse response) {
Cookie cookie = new Cookie("color", null);
cookie.setMaxAge(0); // delete cookie
response.addCookie(cookie);
return "Cookie deleted";
}