问题描述
我使用的是Jersey 1.17.1,在我创建的每个URL上,我都希望允许人们将".json"放在末尾.这是我所做的事的一个示例:
I'm using Jersey 1.17.1 and on every URL I've created I want to allow people to put ".json" at the end or not. Here's an example of what I've done:
@GET
@Path("basepath{extension: (\\.json)?}")
public String foobar() {
...
}
最终,我将让他们在".json"或".xml"一词之间进行选择,并且我担心这里的DRY违规.我将不得不将每个@Path更改为此:
Eventually I'm going to let them choose between nothing, ".json" or ".xml" and I'm concerned about my DRY violation here. I'll have to change every @Path to this instead:
@GET
@Path("basepath{extension: (\\.json|\\.xml)?}")
public String foobar() {
...
}
是否有更好的方法可以使我的路径值更可重用?尽管我无法使用Jersey 2.0,但我很想知道它是否可以解决此问题.
Is there a better way to do this that lets my path value be more reusable? Although I can't use Jersey 2.0, I'd be interested to know if it can solve this problem.
推荐答案
一种方法是将 PackagesResourceConfig 并通知Jersey哪些扩展应映射到哪种媒体类型.例如:
One way to do this is to subclass PackagesResourceConfig and inform Jersey which extensions should map to which media types. For instance:
public class ExampleResourceConfig extends PackagesResourceConfig {
@Override
public Map<String, MediaType> getMediaTypeMappings() {
Map<String, MediaType> map = new HashMap<>();
map.put("xml", MediaType.APPLICATION_XML_TYPE);
map.put("json", MediaType.APPLICATION_JSON_TYPE);
return map;
}
}
,然后您的实际REST服务可能类似于:
and then your actual REST service might look like:
@GET
@Path("basepath")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response foobar() {
...
}
Jersey将根据url扩展名选择适当的媒体类型.请注意,返回的是Response
而不是String
.我不确定您如何构建响应以及您的要求是什么,但是Jersey可以毫无问题地将Java bean转换为XML或JSON(甚至JSONP).
Jersey will select the appropriate media type based on the url extension. Note that Response
is returned instead of String
. I'm not sure how you're building your response and what your requirements are but Jersey can handle converting your Java beans into either XML or JSON (or even JSONP) without a problem.
这篇关于泽西岛:有一种干净的方法来指定允许的URL扩展吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!