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?
The @Produces annotation is used to specify the MIME media types or representations a resource can produce and send back to the client. If @Produces is applied at the class level, all the methods in a resource can produce the specified MIME types by default.
Jersey is Sun's production quality reference implementation for JSR 311: JAX-RS: The Java API for RESTful Web Services. Jersey implements support for the annotations defined in JSR-311, making it easy for developers to build RESTful web services with Java and the Java JVM.
Jersey is a Java library for both serving and calling REST (or mainly HTTP, since not everything is REST) APIs. It's build on top of Java EE specifications, so it can be used on any server that implements these specifications, e.g. Tomcat. In your web. xml file you can define multiple servlets.
Jersey is an open source framework for developing RESTful Web Services. It serves as a reference implementation of JAX-RS. In this article, we'll explore the creation of a RESTful Web Service using Jersey 2. Also, we'll use Spring's Dependency Injection (DI) with Java configuration.
@Produces
annotationThe @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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With