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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23858807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:36:15  来源:igfitidea点击:

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

javarestservicejax-rs

提问by user3673948

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 SearchRequestobject 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 doSearchmethod?

我的问题是如何在doSearch方法的上下文中访问cookie ?

采纳答案by toniedzwiedz

You can use the javax.ws.rs.CookieParamannotation 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 Cookieclass used here is javax.ws.rs.core.Cookiebut 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)
  3. has a constructor that accepts a single Stringargument
  4. has a static method named valueOfor fromStringthat accepts a single Stringargument (see, for example, Integer.valueOf(String))
  5. havs a registered implementation of ParamConverterProviderJAX-RS extension SPI that returns a ParamConverterinstance capable of a "from string" conversion for the type.
  6. Be List<T>, Set<T>or SortedSet<T>, where Tsatisfies 2, 3, 4 or 5 above. The resulting collection is read-only.
  1. 是原始类型
  2. 是一个Cookie(与上面的例子相同)
  3. 有一个接受单个String参数的构造函数
  4. 有一个名为valueOffromString接受单个String参数的静态方法(参见,例如,Integer.valueOf(String)
  5. 有一个ParamConverterProviderJAX-RS 扩展 SPI的注册实现,它返回一个ParamConverter能够对该类型进行“从字符串”转换的实例。
  6. List<T>Set<T>或者SortedSet<T>,其中,T满足2,图3,上述4或5。生成的集合是只读的。

These rules come from the documentation of the @CookieParamannotation as implemented in Jersey, the reference implementation of JAX-RS

这些规则来自在 Jersey 中实现@CookieParam注释文档,JAX-RS 的参考实现