9

I am following the jersey tutorial here to figure out how one would produce multiple mime outputs. From their website, this is the recommended way:

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

What I cannot figure out is how to abstract the @Produces away, so that my code is more welcoming to additional mime types it can produce. Say for example I have 500 methods that all have this annotation:

@Produces({"application/xml", "application/json"})

If I get a requirement to add kml as a mime type, editing and replacing all of those values would certainly be time consuming.

@Produces({"application/xml", "application/json", "application/kml"})

Is it possible to architect @Produces more efficiently so that I do not have this issue down the road?

1 Answer 1

15

Understanding the @Produces annotation

The @Produces annotation is used to specify the MIME media types of representations a resource can produce and send back to the client.

The JAX-RS runtime compares value of the Accept header of an incoming request with the value of the @Produces annotation to match the resource method that will handle such request.

In the absence of the @Produces annotation, support for any media type (*/*) is assumed. For a complete reference, check the JAX-RS specification.

What you can do

To reduce the amount of @Produces annotations in your code, you could annotate the resource classes instead of annotating the resource methods.


Tip: To reduce typographical errors you could use constant values:

@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })

Have a look at the MediaType class.

1
  • 1
    great! exactly what I was looking for! I could not for the life of me find the "support all media" like you mentioned initially. ty
    – angryip
    Jul 21, 2016 at 3:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.