java 泽西岛多种产品
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38488903/
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
Jersey Multiple Produces
提问by angryip
I am following the jersey tutorial hereto figure out how one would produce multiple mime outputs. From their website, this is the recommended way:
我正在关注这里的球衣教程,以弄清楚如何产生多个 mime 输出。从他们的网站,这是推荐的方式:
@GET
@Produces({"application/xml", "application/json"})
public String doGetAsXmlOrJson() {
...
}
What I cannot figure out is how to abstract the @Produces away, so that my code is more welcoming to additional mime types it can produce. Say for example I have 500 methods that all have this annotation:
我无法弄清楚的是如何将 @Produces 抽象出来,以便我的代码更欢迎它可以产生的其他 mime 类型。举例来说,我有 500 个方法都有这个注释:
@Produces({"application/xml", "application/json"})
If I get a requirement to add kml as a mime type, editing and replacing all of those values would certainly be time consuming.
如果我需要将 kml 添加为 mime 类型,那么编辑和替换所有这些值肯定会很耗时。
@Produces({"application/xml", "application/json", "application/kml"})
Is it possible to architect @Produces more efficiently so that I do not have this issue down the road?
是否可以更有效地构建@Produces,以便我以后不会遇到这个问题?
回答by cassiomolin
Understanding the @Produces
annotation
理解@Produces
注释
The @Produces
annotation is used to specify the MIME media types of representations a resource can produce and send back to the client.
该@Produces
注释用于指定MIME媒体类型表示的资源能够产生并发送回客户端的。
The JAX-RS runtime compares value of the Accept
header of an incoming request with the value of the @Produces
annotation to match the resource method that will handle such request.
JAX-RS 运行时将Accept
传入请求的标头值与@Produces
注释值进行比较,以匹配将处理此类请求的资源方法。
In the absence of the @Produces
annotation, support for any media type (*/*
) is assumed. For a complete reference, check the JAX-RS specification.
如果没有@Produces
注释,*/*
则假定支持任何媒体类型 ( )。如需完整参考,请查看JAX-RS 规范。
What you can do
你可以做什么
To reduce the amount of @Produces
annotations in your code, you could annotate the resource classesinstead of annotating the resource methods.
为了减少@Produces
代码中的注释数量,您可以注释资源类而不是注释资源方法。
Tip:To reduce typographical errors you could use constant values:
提示:为了减少印刷错误,您可以使用常量值:
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
Have a look at the MediaType
class.
看看MediaType
班级。