简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM