Cookies are commonly used for session management, tracking user's browsing activity (ad clicks, page visits), storing stateful information (items added to the shopping cart), and much more. They provide a way to persist data that is needed across HTTP requests. Cookies are automatically sent with each HTTP request (visiting a web page, submitting a form, making an asynchronous Ajax request, etc.) by the client.

In this short tutorial, you will learn how to read cookies in a Spring Boot web application. There are multiple ways available to read cookies.

Using @CookieValue Annotation

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

@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, if the cookie is missing from the request, you will get an exception.

Let us supply a defaultValue to avoid the runtime exception:

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

You can also bind multiple cookies to method's parameters by using the @CookieValue annotation:

@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 WebUtils class returns the first cookie with the given name. If no cookie is found in the request, it will return a null value. Let us have 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!";
}

Check out how to use cookies in Spring Boot tutorial to find out more examples for reading and writing cookies in Spring Boot.

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.