@Produces annotation in JAX-RS

99封情书 提交于 2019-12-24 00:58:58

问题


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

回答1:


As it said in 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 specifing 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.




回答2:


JAX-RS methods should base the preferred content type on the value of the Accept header of your request. Failing that, it should default to the first specified.

While the JAX-RS spec is somewhat vague on the subject, the Jersey documentation is very clear in describing the selection mechanism.




回答3:


The @Produces annotation is used by the JAX-RS implementation to bind the incoming request to one of your Resource Methods, based on the accept header of the request.

You can set the exact type of the response in the returned Response object using ResponseBuilder#type(MediaType) if you want to enforce one media type in particular.

If you want to match the accept header of the incoming request ("application/vnd.ms-excel" vs "application/pdf" in your case), you can retrieve that header by adding a parameter annotated with @HeaderParam("accept") in your Java method.

HTH.



来源:https://stackoverflow.com/questions/24257314/produces-annotation-in-jax-rs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!