Spring Boot Get Cookie From Request

In this post, we will see how to get cookies from the request in the Spring Boot application.

1. Using request.getHeader() method – We can get cookie using HttpServletRequest getHeader() method.

String cookie = request.getHeader(HttpHeaders.COOKIE);

2. Using request.getCookie() – We can get all cookies using request.getCookie() method.

    private String getCookie(HttpServletRequest req) {
        for (Cookie cookie : req.getCookies()) {
            if (cookie.getName().equals("some_cookie"))
                return cookie.getValue();
        }
        return null;
    }

Or using Java 8

    private String getCookie(HttpServletRequest req) {
        Cookie [] cookies = req.getCookies();
        boolean isCookieExist= Arrays.stream(cookies).filter(c->
                "cookieName".equals(c.getValue())).findAny().orElse(null);
        return cookie.getValue();

    }

The HttpServletResponse interface contains addCookie() method that used to add cookie in HttpServletResponse.

    private void addCookie(HttpServletResponse response) {
        Cookie cookie= new Cookie("cookie_name", "cookie_value");
        response.addCookie(cookie);
    }

Let’s see some basics about cookie.

A cookie is a piece of information that a server sends to the client(browser). The browser might store it and send it back to server. The cookie has name, value, version, comment, domain, path, and maxAge.

The servlet sends cookies to the browser by using the HttpServletResponse.addCookie() method.

Spring Boot Get Cookie From Request
Spring Boot Get Cookie From Request

Constructors of Cookie class





public Cookie(String name, String value) {
    this.name = name;
    this.value = value;
}

That’s all about Spring Boot Get Cookie From Request.

Other Spring boot tutorial.