Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Produces annotation in JAX-RS

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();
like image 338
akash Avatar asked Sep 20 '25 14:09

akash


2 Answers

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.

like image 74
Robby Cornelissen Avatar answered Sep 22 '25 03:09

Robby Cornelissen


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.

like image 32
Andremoniy Avatar answered Sep 22 '25 05:09

Andremoniy