简体   繁体   English

JAX-RS如何从请求中获取cookie?

[英]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. 因此,我需要访问与用户发送的SearchRequest对象相关联的cookie。

In the SearchRequest class I have only this implementation: 在SearchRequest类中,我只有这个实现:

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. 除了此请求,浏览器还会在用户登录系统时发送cookie集。

My question is how to access the cookie in the context of the doSearch method? 我的问题是如何在doSearch方法的上下文中访问cookie?

You can use the javax.ws.rs.CookieParam annotation on an argument of your method. 您可以在方法的参数上使用javax.ws.rs.CookieParam注释。

@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. 这里使用的Cookie类是javax.ws.rs.core.Cookie但您不必使用它。

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) 是一个Cookie (与上例中的相同)
  3. has a constructor that accepts a single String argument 有一个接受单个String参数的构造函数
  4. has a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String) ) 有一个名为valueOffromString的静态方法,它接受一个String参数(例如,参见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. 有一个ParamConverterProvider JAX-RS扩展SPI的注册实现,它返回一个ParamConverter实例,该实例能够为该类型进行“from string”转换。
  6. Be List<T> , Set<T> or SortedSet<T> , where T satisfies 2, 3, 4 or 5 above. Be List<T>Set<T>SortedSet<T> ,其中T满足上面的2,3,4或5。 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 这些规则来自于Jersey中实现的@CookieParam注释文档,这是JAX-RS的参考实现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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