简体   繁体   English

REST-Jersey-提供跨站点访问

[英]REST - Jersey -Providing Cross Site Access

I guess I am trying to make a few design choices regarding the REST API I'm working on. 我想我正在尝试就我正在使用的REST API做出一些设计选择。

-Is it a good idea to provide cross-site access? -提供跨站点访问是一个好主意吗? In other words, should I allow for JSONP responses. 换句话说,我是否应该允许JSONP响应。 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. 我倾向于提供JSOP响应,因为我猜测如果我不允许JSONP,那么在浏览器中运行的javascript客户端将无法访问我的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 . -使用Jersey,我可以通过使用@Produces("application/javascript")注释我的方法并返回JSONWithPadding的实例来提供JSONP响应。 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) . 上面的示例有效,但我不知道该如何返回javax.ws.rs.core.Response (实例化JSONWithPadding(response, callback)时,Jersey引发异常。

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? 因此,我猜测如果需要将元信息返回给客户端,则需要设计自己的响应类版本吗?

There are lots of ins and outs with JSONP. JSONP有很多来龙去脉。 Have a look at What is JSONP all about? 看看JSONP的全部含义是什么? 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. 在这一点上,如果您想提供从其他域对API的JavaScript访问,则可以采用。 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: 关于第二个问题,我一直在这样做以向客户端提供XML,JSON和JSONP:

@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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM