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();
}
Adding Cookie to HttpServletResponse
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.
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.
- Spring restful web services example using spring boot.
- Spring Data JPA example using spring boot.
- Spring batch basic.
- Spring batch task scheduling example using spring boot.
- Spring transaction management basic.
- Spring transaction management example using spring boot.
- Spring security default authorization example using spring boot.
- Spring security inMemoryAuthentication and authorization example using spring boot.
- @RestController and @Controller annotation example in Spring Boot.
- @RequestBody and @ResponseBody annotation example in Spring Boot.
- @PathVariable and @RequestParam annotations in Spring Boot.
- @RequestHeader annotation example by using Spring Boot.
- @SpringBootApplication annotation example in Spring Boot
- @Component, @Controller, @Service and @Repository annotations example using Spring Boot.
- @ComponentScan example in spring boot.
- Content negotiation example using Spring Boot.
- @Configuration annotation example using spring boot.