Close

Spring MVC - Cookie handling

[Last Updated: Mar 10, 2016]

Reading cookies using @CookieValue

Annotation @CookieValue allows a handler method parameter to be mapped to the value of an Http Cookie:

    @RequestMapping
    public String handleRequest (
                        @CookieValue(value = "myCookieName",
                                            defaultValue = "defaultCookieValue")
                        String cookieValue, Model model) {
        System.out.println(cookieValue);
        ......
        return "my-page";
    }

Like other scenarios, there's an automatic value type conversion. In above example the cookie value is mapped to String type.



Writing Cookies using HttpServletResponse

To write cookies we can use javax.servlet.http.HttpServletResponse:

    @RequestMapping
    public String handleRequest (HttpServletResponse response, Model model) {

        Cookie newCookie = new Cookie("testCookie", "testCookieValue");
        newCookie.setMaxAge(24 * 60 * 60);
        response.addCookie(newCookie);
        .......
        return "my-page";
    }



Using HttpServletRequest to read Cookies:

Instead of using @CookieValue we can also use HttpServletRequest as handler parameter to iterate through or read cookie values.

 @RequestMapping
    public String handleTestRequest (Model model,
                                     HttpServletRequest request){


        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            Arrays.stream(cookies)
                  .forEach(c -> System.out.println(c.getName() + "=" + c.getValue()));
        }
        .......
        return "my-page";
    }

In above example we can also use the static helper method to find a specific cookie: org.springframework.web.util.WebUtils#getCookie(HttpServletRequest request, String name)




Example Project

Dependencies and Technologies Used:

  • Spring Web MVC 4.2.4.RELEASE: Spring Web MVC.
  • Java Servlet API 3.0.1
  • Spring TestContext Framework 4.2.4.RELEASE: Spring TestContext Framework.
  • JUnit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • JDK 1.8
  • Maven 3.0.4

Spring Cookie Handling Example Select All Download
  • spring-cookie-handling
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MyController.java
          • webapp
            • WEB-INF
              • views
        • test
          • java
            • com
              • logicbig
                • example


    Run the web application by using embedded tomcat:

    mvn  clean install tomcat7:run-war
    




    See Also