Question

I'm using Jersey 1.17.1 and on every URL I've created I want to allow people to put ".json" at the end or not. Here's an example of what I've done:

@GET
@Path("basepath{extension: (\\.json)?}")
public String foobar() {
    ...
}

Eventually I'm going to let them choose between nothing, ".json" or ".xml" and I'm concerned about my DRY violation here. I'll have to change every @Path to this instead:

@GET
@Path("basepath{extension: (\\.json|\\.xml)?}")
public String foobar() {
    ...
}

Is there a better way to do this that lets my path value be more reusable? Although I can't use Jersey 2.0, I'd be interested to know if it can solve this problem.

Was it helpful?

Solution

One way to do this is to subclass PackagesResourceConfig and inform Jersey which extensions should map to which media types. For instance:

public class ExampleResourceConfig extends PackagesResourceConfig {
  @Override
  public Map<String, MediaType> getMediaTypeMappings() {
    Map<String, MediaType> map = new HashMap<>();
    map.put("xml", MediaType.APPLICATION_XML_TYPE);
    map.put("json", MediaType.APPLICATION_JSON_TYPE);
    return map;
  }
}

and then your actual REST service might look like:

@GET
@Path("basepath")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response foobar() {
  ...   
}

Jersey will select the appropriate media type based on the url extension. Note that Response is returned instead of String. I'm not sure how you're building your response and what your requirements are but Jersey can handle converting your Java beans into either XML or JSON (or even JSONP) without a problem.

OTHER TIPS

In the REST API implementation , the resource representation can be either xml or json or etc. This is not a good way of restful implementation if you specify the types as the extensions of the URL. The correct way is to use HTTP ACCEPT header

like Accept: application/json or

Accept: application/xml

Refer : http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top