Spring cookies tutorial

Spring cookies tutorial shows how to work with cookies in a Spring application. Cookies are read with @CookieValue annotation.

Spring is a popular Java application framework for creating enterprise applications.


Cookie is a small piece of data that a server sends to the user's web browser. The browser may store it and send it back with the next request to the same server.

Cookies are mainly used for session management, personalization, and tracking.


@CookieValue is an annotation which indicates that a method parameter should be bound to an HTTP cookie.


HttpCookie represents an HTTP cookie as a name-value pair consistent with the content of the "Cookie" request header. The ResponseCookie sub-class has the additional attributes expected in the "Set-Cookie" response header.

Spring cookies example

The following example creates a Spring web application that writes and reads a cookie.

│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           ├───config
│   │           │       MyWebInitializer.java
│   │           │       WebConfig.java
│   │           └───controller
│   │                   MyController.java
│   └───resources
│           logback.xml

This is the project structure of the Spring application.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"












We declare the project dependencies.

<?xml version="1.0" encoding="UTF-8"?>
    <logger name="org.springframework" level="ERROR"/>
    <logger name="com.zetcode" level="INFO"/>

    <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
            <Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n

        <level value="INFO" />
        <appender-ref ref="consoleAppender" />

The logback.xml is a configuration file for the Logback logging library.

package com.zetcode.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MyWebInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

    protected Class<?>[] getRootConfigClasses() {
        return null;

    protected Class<?>[] getServletConfigClasses() {

        return new Class[]{WebConfig.class};

    protected String[] getServletMappings() {

        return new String[]{"/"};

DispatcherServlet, which is a front controller for a Spring web application, is registered in MyWebInitializer.

protected Class<?>[] getServletConfigClasses() {

    return new Class[]{WebConfig.class};

The getServletConfigClasses() returns a web configuration class.

package com.zetcode.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@ComponentScan(basePackages = {"com.zetcode"})
public class WebConfig {


The WebConfig enables Spring MVC annotations with @EnableWebMvc and configures component scanning for the com.zetcode package.

package com.zetcode.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

public class MyController {

    private static final Logger logger = LoggerFactory.getLogger(MyController.class);

    @ResponseStatus(value = HttpStatus.OK)
    @GetMapping(value = "/readCookie")
    public void readCookie(@CookieValue(value = "fav-col",
            defaultValue = "unknown") String favColour) {

        logger.info("Favourite colour: {}", favColour);

    @ResponseStatus(value = HttpStatus.OK)
    @GetMapping(value = "/writeCookie")
    public ResponseEntity writeCookie() {

        var favColour = "steelblue";
        var cookie = ResponseCookie.from("fav-col", favColour).build();

        return ResponseEntity.ok()
                .header(HttpHeaders.SET_COOKIE, cookie.toString())

We have two GET mappings. The first mapping reads a cookie, the second one writes a cookie.

public void readCookie(@CookieValue(value = "fav-col",
        defaultValue = "unknown") String favColour) {

We read a cookie value with @CookieValue. There is a default value if the cookie is not set or has expired.

var favColour = "steelblue";
var cookie = ResponseCookie.from("fav-col", favColour).build();

return ResponseEntity.ok()
        .header(HttpHeaders.SET_COOKIE, cookie.toString())

We create a cookie with ResponseCookie and set it to the response header.

$ mvn jetty:run

We start the Jetty server. Now, first locate the browser to the localhost:8080/writeCookie and then read the cookie by navigating to localhost:8080/readCookie.

In this tutorial, we have work with cookies in Spring. You might also be interested in the related tutorials: Spring @RequestMapping tutorial, Spring @RequestHeader tutorial, Java tutorial, or list all Spring tutorials.