java produces,为什么要使用REST @Produces注释

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());

}

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?

解决方案

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"})

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值