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?
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:
Cookie
(same as in the example above)String
argumentvalueOf
or fromString
that accepts a single String
argument (see, for example, Integer.valueOf(String)
)ParamConverterProvider
JAX-RS extension SPI that returns a ParamConverter
instance capable of a "from string" conversion for the type.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With