Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAX-RS How to get a cookie from a request?

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?

like image 991
user3673948 Avatar asked May 25 '14 18:05

user3673948


1 Answers

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:

  1. is a primitive type
  2. is a Cookie (same as in the example above)
  3. has a constructor that accepts a single String argument
  4. has a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String))
  5. havs a registered implementation of ParamConverterProvider JAX-RS extension SPI that returns a ParamConverter instance capable of a "from string" conversion for the type.
  6. 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

like image 127
toniedzwiedz Avatar answered Nov 03 '22 00:11

toniedzwiedz