JAX-RS How to get cookie from request?

Consider the following method:

@POST @Path("/search") public SearchResponse doSearch(SearchRequest searchRequest); 

I would like this method to know about the user who made the request. Therefore, 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 a cookie when a user logs in.

My question is: how do I access a cookie in the context of the doSearch method?

+7
java rest service jax-rs
source share
1 answer

You can use the javax.ws.rs.CookieParam annotation to argument your method.

 @POST @Path("/search") public SearchResponse doSearch( SearchRequest searchRequest, @CookieParam("cookieName") Cookie cookie ) { //method body } 

The Cookie used here is the javax.ws.rs.core.Cookie class, but you do not need to use it.

You can use this annotation for any argument if:

  • is a primitive type
  • is Cookie (same as in the example above)
  • has a constructor that takes a single argument String
  • has a static method called valueOf or fromString that takes a single String argument (see, for example, Integer.valueOf(String) )
  • has a registered implementation of the ParamConverterProvider extension of the JAX-RS extension, which returns an instance of ParamConverter capable of converting "from a string" to a 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 are taken from the documentation of the @CookieParam annotation implemented in Jersey, the JAX-RS reference implementation

+9
source share

All Articles