@Produces JAX-RS 中的注解 [英] @Produces annotation in JAX-RS

查看:31
本文介绍了@Produces JAX-RS 中的注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务方法产生这个 MediaTypes 之一,它可能产生 pdfexcel 文件或其他.

@Produces({"application/pdf","application/vnd.ms-excel"...

我的问题

我的服务总是返回带有 application/pdf 的响应类型,即使它产生 excel.为什么?

我重新排列了MediaTypes.

@Produces({"application/vnd.ms-excel","application/pdf",...

现在它为所有响应提供 application/vnd.ms-excel 类型,又是为什么?

我正在为客户端使用 com.sun.jersey API 并通过使用

获取类型

clientResponse.getType()

可能我想我误解了@Produces注解的概念.

请澄清.

<小时>

以下是我的服务方法的代码.

response = Response.ok((Object) file);//文件是文件的对象response.header("Content-Disposition","attachment; filename="+filename);//文件名可以是a.pdf b.xlsx等返回 response.build();

解决方案

正如它在 文档:

@GET@Produces({"application/xml", "application/json"})公共字符串 doGetAsXmlOrJson() {...}

<块引用>

如果可以接受媒体类型application/xml"和application/json"中的任一种,则会调用 doGetAsXmlOrJson 方法.如果两者都可以接受,则会选择前者,因为它先出现.

此外,您可以使用 quality factor 来指定更可取的媒体类型:@Produces({"application/xml; qs=0.9", "application/json"}).

无论如何,如果您想确定使用的是哪种媒体类型,您应该将您的方法分成两个不同的签名.

My service method Produces one of this MediaTypes it may produce pdf or excel file or other.

@Produces({"application/pdf","application/vnd.ms-excel"...

My Question

My service returns response type with application/pdf always even if it produces excel. Why?

Than I rearranged MediaTypes.

@Produces({"application/vnd.ms-excel","application/pdf",...

Now it's giving type application/vnd.ms-excel for all responses,again Why?

I am using com.sun.jersey API for client and getting type by the use of

clientResponse.getType()

Probably I think I misunderstood the concept of @Produces annotation.

Please Clarify.


Following is code of my Service method.

response = Response.ok((Object) file);//file is Object of File
response.header("Content-Disposition","attachment; filename="+filename);
//filename can be a.pdf b.xlsx etc
return response.build();

解决方案

As it said in the documenation:

@GET
@Produces({"application/xml", "application/json"})
public String doGetAsXmlOrJson() {
    ...
}

The doGetAsXmlOrJson method will get invoked if either of the media types "application/xml" and "application/json" are acceptable. If both are equally acceptable then the former will be chosen because it occurs first.

Also, you can use quality factor for specifying which media type is more preferable: @Produces({"application/xml; qs=0.9", "application/json"}).

In any way, if you want to be sure about which media type is used, you should divide your methods into two different signatures.

这篇关于@Produces JAX-RS 中的注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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