JAX-RS How to get a cookie from a request?
java, jax-rs, rest, service
Solution
You can use the `javax.ws.rs.CookieParam` annotation on an argument of your method.
@POST
@Path("/search")
public SearchResponse doSearch(
SearchRequest searchRequest,
@CookieParam("cookieName") Cookie cookie
) {
//method body
}
The `Cookie` class used here is `javax.ws.rs.core.Cookie` but you don't have to use it.
You can use this annotation on any argument as long as is:
- is a primitive type
- is a `Cookie` (same as in the example above)
- has a constructor that accepts a single `String` argument
- has a static method named `valueOf` or `fromString` that accepts a single `String` argument (see, for example, `Integer.valueOf(String)`)
- havs a registered implementation of `ParamConverterProvider` JAX-RS extension SPI that returns a `ParamConverter` instance capable of a "from string" conversion for the type.
- Be `List<T>`, `Set<T>` or `SortedSet<T>`, where `T` satisfies 2, 3, 4 or 5 above. The resulting collection is read-only.
These rules come from the documentation of the `@CookieParam` annotation as implemented in Jersey, the reference implementation of JAX-RS
Problem
Consider the following method: ``` @POST @Path("/search") public SearchResponse doSearch(SearchRequest searchRequest); ``` I would like this method to be aware of the user who made the request. As such, I need access to the cookie associated with the `SearchRequest` object sent from the user. In the SearchRequest class I have only this implementation: ``` public class SearchRequest { private String ipAddress; private String message; ... ``` And here is the request: ``` { "ipAddress":"0.0.0.0", "message":"foobarfoobar" } ``` Along with this request, the browser sends the cookie set when the user signed into the system. My question is how to access the cookie in the context of the `doSearch` method?