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

為{幸葍}努か 提交于 2019-12-23 17:30:16

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/18861071/jersey-is-there-a-clean-way-to-specify-allowed-url-extensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!