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?

angryip
  • 2,140
  • 5
  • 33
  • 67

1 Answers1

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.

Community
  • 1
  • 1
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • 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 '16 at 03:18