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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:26:44  来源:igfitidea点击:

Jersey Multiple Produces

javajerseyjax-rs

提问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 @Producesannotation

理解@Produces注释

The @Producesannotation 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 Acceptheader of an incoming request with the value of the @Producesannotation to match the resource method that will handle such request.

JAX-RS 运行时将Accept传入请求的标头值与@Produces注释值进行比较,以匹配将处理此类请求的资源方法。

In the absence of the @Producesannotation, 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 @Producesannotations 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 MediaTypeclass.

看看MediaType班级。