Joe
Joe

Reputation: 71

JAX-RS Jersey - Howto force a Response ContentType? Overwrite content negotiation

Jersey identifies requests by looking at the accept header. I have a request which accepts only text/* - How can i force the response to be for example application/json?

@POST
@Path("/create")
@Produces(MediaType.APPLICATION_JSON)
public MyResponseObject create() {
    return new MyResponseObject();
}

If a request is directed to create which only accepts text/* jersey will return a 500. Is there a way to workaround this issue? (I can't change the requests accept header).

Upvotes: 3

Views: 3792

Answers (2)

Arul Dhesiaseelan
Arul Dhesiaseelan

Reputation: 2009

Jersey also supports this via ResourceConfig property PROPERTY_MEDIA_TYPE_MAPPINGS that you could configure in your web.xml or programatically via Jersey APIs as shown below:

 DefaultResourceConfig rc = new DefaultResourceConfig(MyResource.class);
 rc.getMediaTypeMappings().put("json", MediaType.APPLICATION_JSON_TYPE);
 rc.getMediaTypeMappings().put("xml", MediaType.APPLICATION_XML_TYPE);
 SimpleServerFactory.create("http://localhost:9090", rc);

You can force content type negotiation by suffixing either .json or .xml to your URL.

Upvotes: 5

Joe
Joe

Reputation: 71

I solved this by using a servlet filter:

http://www.zienit.nl/blog/2010/01/rest/control-jax-rs-content-negotiation-with-filters

Upvotes: 4

Related Questions