[JAVA] Get cookies in Spring

A common practice was to getCookies from HttpServletRequest and retrieve from it. It looks like this:

CookieController.java


    @GetMapping("cookies3")
    public String showCookies3(HttpServletRequest httpServletRequest) {
        Cookie[] cookies = httpServletRequest.getCookies();
        Arrays.stream(cookies).forEach(cookie -> System.out.println(cookie.getValue()));
        return VIEW_NAME;
    }

However, you can get it a little easier by using Spring.

Cookie generation

Set the cookie appropriately.

CookieController.java



    private final String VIEW_NAME = "demo/cookie/index";

    @GetMapping("/")
    public String index(HttpServletResponse httpServletResponse) {
        httpServletResponse.addCookie(new Cookie("key1", "value1"));
        return VIEW_NAME;
   }

Get cookies

It can be easily obtained by using the CookieValue annotation as shown below. The argument is the cookie key value.

CookieController.java



    private final String VIEW_NAME = "demo/cookie/index";

    @GetMapping("cookies1")
    public String showCookies1(@CookieValue("key1") String cookieValue) {
        System.out.println(cookieValue);
        return VIEW_NAME;
    }

However, if the above writing method is used and the cookie cannot be obtained due to deletion, a runtime error will occur. ※Resolved [org.springframework.web.bind.MissingRequestCookieException: Missing cookie 'key1' for method parameter of type String])

Therefore, it can be avoided by setting required of @CookieValue to false (default is required = true) as shown below.

However, in this case, null is set in the argument, so by specifying the defaultValue attribute, it is possible to specify the default value if it cannot be obtained from the cookie.

CookieController.java



    private final String VIEW_NAME = "demo/cookie/index";

    @GetMapping("cookies2")
    public String showCookies2(
            @CookieValue(name = "key1", required = false, defaultValue = "default value1") String cookieValue) {
        System.out.println(cookieValue);
        return VIEW_NAME;
    }

that's all.

Recommended Posts

Get cookies in Spring
Inject Logger in Spring
Use Interceptor in Spring
Microservices in Spring Cloud
Get multiple Resources that match the pattern in spring
Get UserAgent in [Rails] controller
Get EXIF information in Java
Get started with Spring boot
Spring Boot 2 multi-project in Gradle
[Java] Get KClass in Java [Kotlin]
Error in Spring database connection
Major changes in Spring Boot 1.5
NoHttpResponseException in Spring Boot + WireMock
Loop step in Spring Batch
Get error information using DefaultErrorAttributes and ErrorAttributeOptions in Spring Boot 2.3
How to use Lombok in Spring
Spring Boot Hello World in Eclipse
Spring Boot application development in Eclipse
Java Spring environment in vs Code
Write test code in Spring Boot
[Java] Get data from DB using singleton service in Spring (Boot)
Get Null-safe Map values in Java
How to get parameters in Spark
Implement reCAPTCHA v3 in Java / Spring
Get validation results with Spring Boot
Store session information in database in Spring Session
OkHttp3 (GET, POST) in Android Studio
Implement REST API in Spring Boot
What is @Autowired in Spring boot?
Event processing is performed in Spring.
Implement Spring Boot application in Gradle
Thymeleaf usage notes in Spring Boot
How to get the setting value (property value) from the database in Spring Framework
Get the result of POST in Java
How to get date data in Ruby
Spring Autowired is written in the constructor
Launch (old) Spring Boot project in IntelliJ
Convert request parameter to Enum in Spring
Get in touch with Eclipse MicroProfile Health
Exists using Specification in Spring Data JPA
Output Spring Boot log in json format
Local file download memorandum in Spring Boot
Create Java Spring Boot project in IntelliJ
Loosen Thymeleaf syntax checking in Spring Boot
Error in implementation when implementing Spring validation
Separate Task Executors used in Spring @Async
[Practice! ] Display Hello World in Spring Boot
How Dispatcher servlet works in Spring MVC
Use DynamoDB query method in Spring Boot
Null support cache in Spring Data Redis
To write Response data directly in Spring
How to get the date in java
Major changes in Spring Framework 5.0 core functionality
Get history from Zabbix server in Java
Switching beans by profile annotation in Spring
DI SessionScope Bean in Spring Boot 2 Filter
[* Java *] I participated in JJUG CCC 2019 Spring
Maven configuration problem in Spring pom.xml in Eclipse
Change session timeout time in Spring Boot
Get weather forecast from OpenWeatherMap in Rails
File output bean as JSON in spring