为什么要使用REST @Produces注释 [英] Why use REST @Produces annotation

查看:2568
本文介绍了为什么要使用REST @Produces注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我明白你是在指定类型,但为什么呢?在什么条件下才重要。例如,如果我有以下方法,并且我注释掉@Produces注释,它仍然返回JSON。

So I understand that you are specifying the type, but why? Under what conditions would it matter. For example, if I have the following method, and I comment out the @Produces annotation, it still returns JSON.

@GET
@Path("/json")
//@Produces({MediaType.APPLICATION_JSON})
public String getJson(){
    return toJson(getResults());
}

API文档说'如果没有指定,那么容器将假定任何类型可以生成。'那么为什么我不希望容器假设?

The API doc says 'If not specified then a container will assume that any type can be produced.' So why would I not want the container to assume that?

推荐答案

我认为这取决于你的JAX- RS实现,但这里是泽西岛对其@Produces注释的解释: https://jersey.java.net/ documentation / latest / jaxrs-resources.html#d0e1809

I think it depends on your JAX-RS implementation but here's Jersey's explanation of their @Produces annotation: https://jersey.java.net/documentation/latest/jaxrs-resources.html#d0e1809

基本上,客户端需要确定服务器应该回吐的内容类型。
如果客户端支持多种内容类型,则有时可以为给定方法指定要返回的内容类型的优先级:

Basically, it's up to the client to determine what content type the server should spit back. If the client supports more than one content type, you can sometimes specify the priority of content types to return, for a given method:

@Produces({"application/xml; qs=0.9", "application/json"})




在上面的示例中,如果客户端同时接受application / xml和application / json(同样),那么服务器总是发送application / json,因为application / xml质量因子较低。

In the above sample, if client accepts both "application/xml" and "application/json" (equally), then a server always sends "application/json", since "application/xml" has a lower quality factor.

这篇关于为什么要使用REST @Produces注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆