How to read cookies in Spring Boot

There are three ways to read HTTP cookies in Spring Boot:

  1. Use the @CookieValue annotation to read an individual cookie.
  2. The WebUtils class provides utility methods to fetch information from the request object.
  3. The HttpServletRequest class that retrieves all cookies as an array.

Using @CookieValue Annotation

The simplest way to read a cookie value in Spring Boot is using the @CookieValue annotation. It indicates that the controller's method parameter is bound to an HTTP cookie:

@GetMapping("/profile")
public String profilePage(@CookieValue(name = "color") String color) {
    return "You are using " + color + " mode.";
}

The @CookieValue annotation takes several parameters:

  • name — The name of the cookie to bind the method's parameter.
  • required — Whether the cookie is required. Defaults to true, leading to an exception if the cookie is missing in the request. Switching this to false will set the cookie value to null if the cookie is absent from the request.
  • defaultValue — The default value to use as a fallback. Passing a default value will automatically set required to false.

In the example above, if a cookie with the name color is present in the HTTP request, the variable color will contain its value. Otherwise, an exception will be thrown.

To avoid the runtime exception, use the defaultValue parameter:

@GetMapping("/profile")
public String profilePage(@CookieValue(name = "color", defaultValue = "dark") String color) {
    return "You are using " + color + " mode.";
}

You can also add multiple @CookieValue annotations to bind more than one controller method parameter:

@GetMapping("/profile")
public String profilePage(@CookieValue(name = "name", defaultValue = "Atta") String name,
                              @CookieValue(name = "country", defaultValue = "PK") String country) {
    return "I'm " + name + " from " + country;
}

Using WebUtils Class

The WebUtils class provides built-in utilities for web applications to manipulate the incoming HTTP requests. Using this utility class, we can easily fetch information from the request object.

The getCookie() method from the WebUtils class returns the first cookie with the given name. Otherwise, a null value is returned.

Here is an example:

@GetMapping("/profile")
public String profilePage(HttpServletRequest request) {
    Cookie name = WebUtils.getCookie(request, "name");
    if (name != null) {
        return "My name is " + name.getValue();
    } else {
        return "Not found!";
    }
}

Using HttpServletRequest Class

The HttpServletRequest class provides request information for HTTP servlets. You can call the getCookies() method on its object to retrieve an array of Cookie objects that the client sent with this request. This method returns null if no cookies were sent.

@GetMapping("/preferences")
public String preferencesPage(HttpServletRequest request) {

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

    return "No preferences found!";
}

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.