A web cookie is a small piece of data that is stored by the server in the user's browser to track user behavior, facilitate session management, and more. The cookie is sent to the client browser while returning the response for an HTTP request.

Her is an example that shows how to set a cookie while sending back ResponseEntity as response for a RESTful web service:

@GetMapping("/login")
@ResponseBody
public ResponseEntity<?> login(@RequestBody String credentials, HttpServletResponse response) {

    // create a cookie
    Cookie cookie = new Cookie("platform","mobile");

    // expires in 7 days
    cookie.setMaxAge(7 * 24 * 60 * 60);

    // optional properties
    cookie.setSecure(true);
    cookie.setHttpOnly(true);
    cookie.setPath("/");

    // add cookie to response
    response.addCookie(cookie);

    // TODO: add your login logic here
    String jwtToken = "NOT_AVAILABLE";

    // return response entity
    return new ResponseEntity<>(jwtToken, HttpStatus.OK);
}

The above code uses HttpServletResponse to add a cookie to the response. Here are how the response headers look like:

HTTP/1.1 200
Set-Cookie: platform=mobile; Max-Age=604800; Expires=Sat, 10-Aug-2019 12:14:41 GMT; Path=/; Secure; HttpOnly
Content-Type: text/html;charset=UTF-8
Content-Length: 13
Date: Sat, 03 Aug 2019 12:14:41 GMT

Another way is to add the cookie as raw Set-Cookie header while building ResponseEntity object:

HttpHeaders headers = new HttpHeaders();
headers.add("Set-Cookie","platform=mobile; Max-Age=604800; Path=/; Secure; HttpOnly");
ResponseEntity.status(HttpStatus.OK).headers(headers).build();

Check out how to use cookies in Spring Boot guide to find out more options 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.