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
JAX-RS How to get a cookie from a request?
提问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 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 ?
采纳答案by toniedzwiedz
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:
您可以在任何参数上使用此注释,只要:
- is a primitive type
- is a
Cookie
(same as in the example above) - has a constructor that accepts a single
String
argument - has a static method named
valueOf
orfromString
that accepts a singleString
argument (see, for example,Integer.valueOf(String)
) - havs a registered implementation of
ParamConverterProvider
JAX-RS extension SPI that returns aParamConverter
instance capable of a "from string" conversion for the type. - Be
List<T>
,Set<T>
orSortedSet<T>
, whereT
satisfies 2, 3, 4 or 5 above. The resulting collection is read-only.
- 是原始类型
- 是一个
Cookie
(与上面的例子相同) - 有一个接受单个
String
参数的构造函数 - 有一个名为
valueOf
或fromString
接受单个String
参数的静态方法(参见,例如,Integer.valueOf(String)
) - 有一个
ParamConverterProvider
JAX-RS 扩展 SPI的注册实现,它返回一个ParamConverter
能够对该类型进行“从字符串”转换的实例。 - 是
List<T>
,Set<T>
或者SortedSet<T>
,其中,T
满足2,图3,上述4或5。生成的集合是只读的。
These rules come from the documentation of the @CookieParam
annotation as implemented in Jersey, the reference implementation of JAX-RS