DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Be Punctual! Avoiding Kotlin’s lateinit In Spring Boot Testing
  • 5 Best Java Frameworks for Web Development in 2023
  • Spring Boot: How To Use Java Persistence Query Language (JPQL)
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)

Trending

  • Docker Base Images Demystified: A Practical Guide
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Unlocking AI Coding Assistants Part 4: Generate Spring Boot Application
  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  1. DZone
  2. Coding
  3. Java
  4. How to Use Cookies in Spring Boot

How to Use Cookies in Spring Boot

Check out this post to learn more about using web cookies in Spring Boot.

By 
Atta Shah user avatar
Atta Shah
·
Updated Jul. 30, 19 · Tutorial
Likes (20)
Comment
Save
Tweet
Share
230.9K Views

Join the DZone community and get the full member experience.

Join For Free

An HTTP Cookie (also known as a web cookie or browser cookie) is a small piece of information stored by the server in the user's browser. The server sets the cookies while returning the response for a request made by the browser. The browser stores the cookies and sends them back with the next request to the same server. Cookies are generally used for session management, user-tracking, and to store user preferences.

Cookies help server remember the client across multiple requests. Without cookies, the server would treat every request as a new client.

In this tutorial, we will learn how to read, set, and remove HTTP cookies in a Spring Boot application.

Reading HTTP Cookie

The Spring Framework provides the @CookieValue annotation to get the value of any HTTP cookie without iterating over all the cookies fetched from the request. This annotation can be used to map the value of a cookie to the controller method parameter.

@GetMapping("/")
public String readCookie(@CookieValue(value = "username", defaultValue = "Atta") String username) {
    return "Hey! My username is " + username;
}


In the above code snippet, notice the defaultValue = "Atta". If the default value is not set, Spring will throw a java.lang.IllegalStateException exception on failure to find the cookie with name username in HTTP request.

Setting HTTP Cookie

To set a cookie in Spring Boot, we can use HttpServletResponse class's method addCookie(). All you need to do is to create a new instance of Cookie class and add it to the response.

@GetMapping("/change-username")
public String setCookie(HttpServletResponse response) {
    // create a cookie
    Cookie cookie = new Cookie("username", "Jovan");

    //add cookie to response
    response.addCookie(cookie);

    return "Username is changed!";
}


Reading All Cookies

Instead of using @CookieValue annotation, we can also use HttpServletRequest class as a controller method parameter to read all cookies. This class provides getCookies() method, which returns all cookies sent by the browser as an array of Cookie.

@GetMapping("/all-cookies")
public String readAllCookies(HttpServletRequest request) {

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        return Arrays.stream(cookies)
                .map(c -> c.getName() + "=" + c.getValue()).collect(Collectors.joining(", "));
    }

    return "No cookies";
}


Cookie Expiration

If no expiration time is specified for a cookie, it lasts as long as the session is not expired. Such cookies are called session cookies. Session cookies remain active until the user closes their browser or clears their cookies. The username cookie created above is in fact a session cookie.

But you can override this default behavior and set the cookie expiration time using setMaxAge() method of Cookie class.

// create a cookie
Cookie cookie = new Cookie("username", "Jovan");
cookie.setMaxAge(7 * 24 * 60 * 60); // expires in 7 days

//add cookie to response
response.addCookie(cookie);


Now, instead of expiring when the browser is closed, the username cookie will remain active for the next 7 days. Such cookies, which expire at a specified date and time, are called permanent cookies.

The expiry time passed to setMaxAge() method is in seconds. The expiry date and time is relative to the client where the cookie is being set, not the server.

Secure Cookie

A secure cookie is the one which is only sent to the server over an encrypted HTTPS connection. Secure cookies cannot be transmitted to the server over unencrypted HTTP connections.

// create a cookie
Cookie cookie = new Cookie("username", "Jovan");
cookie.setMaxAge(7 * 24 * 60 * 60); // expires in 7 days
cookie.setSecure(true);

//add cookie to response
response.addCookie(cookie);

HttpOnly Cookie


HttpOnly cookies are used to prevent cross-site scripting (XSS) attacks and are not accessible via JavaScript's Document.cookie API. When the HttpOnly flag is set for a cookie, it tells the browser that this particular cookie should only be accessed by the server.

// create a cookie
Cookie cookie = new Cookie("username", "Jovan");
cookie.setMaxAge(7 * 24 * 60 * 60); // expires in 7 days
cookie.setSecure(true);
cookie.setHttpOnly(true);

//add cookie to response
response.addCookie(cookie);

Cookie Scope

If the scope is not specified, a cookie is only sent to the server for a path that was used to set it in the browser. We can change this behavior using setPath() method of the Cookie class. This sets the Path directive for the cookie.

// create a cookie
Cookie cookie = new Cookie("username", "Jovan");
cookie.setMaxAge(7 * 24 * 60 * 60); // expires in 7 days
cookie.setSecure(true);
cookie.setHttpOnly(true);
cookie.setPath("/"); // global cookie accessible every where

//add cookie to response
response.addCookie(cookie);


Deleting Cookie

To delete a cookie, set the Max-Age directive to 0 and unset its value. You must also pass the same other cookie properties you used to set it. Don't set the Max-Age directive value to -1. Otherwise, it will be treated as a session cookie by the browser.

// create a cookie
Cookie cookie = new Cookie("username", null);
cookie.setMaxAge(0);
cookie.setSecure(true);
cookie.setHttpOnly(true);
cookie.setPath("/");

//add cookie to response
response.addCookie(cookie);

Source code: Download the complete source code from GitHub available under MIT license.

Summary

Cookies provide a way to exchange the information between the server and the browser to manage sessions (logins, shopping carts, game scores), remember user preferences (themes, privacy policy acceptance), and to track the user behavior across the site.

Spring Boot provides an easy way to read, write, and remove HTTP cookies.

  • @CookieValue annotation maps the value of the cookie to the method parameter. You should set the default value to avoid runtime exception when the cookie is not available.
  • HttpServletResponse class can be used to set a new cookie in the browser. You just need to create an instance of Cookie class and add it to the response.
  • To read all cookies, you can use HttpServletRequest's getCookies() method which returns an array of Cookie.
  • Max-Age directive specifies the date and time when the cookie should expire.
  • If you are storing sensitive information in a cookie, make sure to set Secure and HttpOnly flags to avoid XSS attacks.
  • Set the Path=/ to make a cookie accessible everywhere for the current domain.
  • To delete a cookie, set the Max-Age to 0 and pass all the properties you used to set it.

That's all, folks, for using cookies in a Spring Boot application. If you have any question or feedback, please feel free to send me a tweet anytime.

This article was originally published on attacomsian.com/blog.

Spring Framework Spring Boot Web development Java (programming language)

Published at DZone with permission of Atta Shah. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Be Punctual! Avoiding Kotlin’s lateinit In Spring Boot Testing
  • 5 Best Java Frameworks for Web Development in 2023
  • Spring Boot: How To Use Java Persistence Query Language (JPQL)
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!