REST - Jersey -Providing Cross Site Access

眉间皱痕 提交于 2019-12-12 03:05:15

问题


I guess I am trying to make a few design choices regarding the REST API I'm working on.

-Is it a good idea to provide cross-site access? In other words, should I allow for JSONP responses. I'm leaning toward providing JSOP responses, because I'm guessing that if I don't allow for JSONP, then a javascript client running in a browser will not be able to access my API. If you have any experience For or Against this idea, I'd appreciate it.

-Using Jersey, I can provide JSONP response by annotating my methods with a @Produces("application/javascript") and returning an instance of JSONWithPadding. Like so:

    @GET
    @Produces("application/javascript")
    @Path("{film_id}")
    public JSONWithPadding crossSitefilmWithID(
                @DefaultValue(NO_ID) @PathParam("film_id") final String filmId,
                @DefaultValue(CALLBACK) @QueryParam("callback") String callback) {
    ....
        return new JSONWithPadding(films.get(id), callback);
    }

The above example works, but I can't figure out how I would return a javax.ws.rs.core.Response instead (Jersey throws an exception when I instantiate a JSONWithPadding(response, callback).

So I'm guessing that if I need to return meta-information to the client, I need to devise my own version of response class?


回答1:


There are lots of ins and outs with JSONP. Have a look at What is JSONP all about? for more information. At this point if you want to offer JavaScript access to your API from other domains it's the way to go. If it makes sense for your application is up to you.

As to the second question I do this all the time to provide XML, JSON, and JSONP to clients:

@GET
@Path("/thing")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, CustomMediaTypes.APPLICATION_JSONP})
public Response doThing(@QueryParam("callback") @DefaultValue("fn") String callback) {      
  // Do the thing
  GenericEntity<MyThing> response = new GenericEntity<MyThing>(thing){};
  return Response.ok(new JSONWithPadding(response, callback)).build();
}


来源:https://stackoverflow.com/questions/15261640/rest-jersey-providing-cross-site-access

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