Cookie Manipulation In Spring Boot
In this blog, we’ll explore how to use cookies in a Spring Boot application.
So, what is a cookie?
A cookie is a small piece of information stored in the user's web browser. For the Chrome browser, the maximum number of cookies is 300, and per cookie size is 4096 bytes.
Typically cookies contain information about the user’s activity or preferences like personalized content, login management, and many more.
Here I give some hands-on examples of cookies functionality, Like
1. Set-Cookie
2. Get Cookie
3. Set Expiry of cookie
4. Delete Cookie
1. Set-Cookie
The HttpServletResponse class is used to set a new cookie with a Cookie
class instance.
2. Get-Cookie
@CookieValue makes it easy to grab a cookie from a user’s request. If the cookie you’re looking for isn’t there, it throws MissingRequestCookieException. You can handle this by setting a default value.
3. Set Expiry of Cookie
When setting the expiration of cookies, we use the setMaxAge method and provide the duration in seconds. A negative value means the cookie won’t be stored, zero means it will be deleted, and positive values indicate the valid expiration time in seconds.
4. Delete Cookie
To delete a cookie, set its setMaxAge to 0 and unset its value.
Reff: Header Image | Code Snippet
Git Repository: https://github.com/fesabelilla/cookie-manipulation-springboot