如何在Jersey 1.x的服务器端为传入请求设置Accept标头 [英] How to set Accept header on the server side in Jersey 1.x for an incoming request
问题描述
我想知道是否可以在服务器端为传入请求设置"Accept"标头.
I would like to know if there is a way to set the "Accept" headers for an incoming request on server side.
在Jersey 2.x中可以通过实现和注册@prematching ContainerRequestFilter来做到这一点,但是我还没有找到在Jersey 1.x版本中实现相同功能的方法.
This is possible to do in Jersey 2.x by implementing and registering a @prematching ContainerRequestFilter but I have not found a way to achieve the same in Jersey 1.x versions.
这个想法是在资源方法上设置一个"Accept"标头,该标头可以通过"@Produces"注释来理解.我正在尝试处理客户端无法设置"Accept"标头的用例.因此,他将期望的响应类型指定为查询参数,例如"type = json".想法是最好在过滤器中读取提供的类型查询参数,并在调用带有"@Produces"注释的资源方法之前更新"Accept"标头.
The idea is to set an "Accept" header that is understood by '@Produces' annotation on a resource method. I am trying to handle a use case where the client cannot set an "Accept" header. So he specifies the kind of response he expects as a query parameter such as "type=json". The idea is to read the supplied type query parameter preferably in a filter and update the "Accept" header before the resource method with the '@Produces' annotation is called.
请让我知道是否有办法实现这一目标.
Please let me know if there is a way to achieve this.
最诚挚的问候,
推荐答案
我认为实现此目的的首选方法是使用网址扩展名.
I think the preferred way to do this is with url extensions.
http://example.org/resource.xml
将返回XML.
http://example.org/resource.json
将返回JSON.
这可以通过自定义PackagesResourceConfig
告诉Jersey如何将扩展名映射到媒体类型来实现:
This can be implemented with a custom PackagesResourceConfig
telling Jersey how to map extensions to media types:
public class ExampleResourceConfig extends PackagesResourceConfig {
public ExampleResourceConfig(Map<String, Object> props) {
super(props);
}
public ExampleResourceConfig(String... packages) {
super(packages);
}
@Override
public Map<String, MediaType> getMediaTypeMappings() {
Map<String, MediaType> map = newHashMap();
map.put("xml", MediaType.APPLICATION_XML_TYPE);
map.put("json", MediaType.APPLICATION_JSON_TYPE);
return map;
}
}
如果您使用web.xml
来配置Jersey,则可以将javax.ws.rs.Application
属性设置为您的PackagesResourceConfig
类名称.
If you're using a web.xml
to configure Jersey you can set the javax.ws.rs.Application
property to your PackagesResourceConfig
class name.
这篇关于如何在Jersey 1.x的服务器端为传入请求设置Accept标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!