javarestjerseyjersey-1.0

Jersey: Is there a clean way to specify allowed URL extensions?


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.


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.