REST-Jersey-提供跨站点访问 [英] REST - Jersey -Providing Cross Site Access

查看:99
本文介绍了REST-Jersey-提供跨站点访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我正在就我正在使用的REST API做出一些设计选择.

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

-提供跨站点访问是一个好主意吗?换句话说,我应该允许 JSONP 响应.我倾向于提供JSOP响应,因为我猜测如果我不允许JSONP,那么在浏览器中运行的javascript客户端将无法访问我的API.如果您有任何支持或反对此想法的经验,我将不胜感激.

-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.

-使用Jersey,我可以通过用@Produces("application/javascript")注释我的方法并返回JSONWithPadding的实例来提供JSONP响应.像这样:

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

上面的示例有效,但是我无法弄清楚如何返回javax.ws.rs.core.Response(实例化JSONWithPadding(response, callback)时,Jersey引发异常.

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?

推荐答案

JSONP的来龙去脉.有关更多信息,请查看 JSONP的全部含义是什么.在这一点上,如果要提供从其他域对API的JavaScript访问,则可以采用.如果您的应用程序适合您,则由您决定.

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.

关于第二个问题,我一直在这样做,以向客户端提供XML,JSON和JSONP:

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

这篇关于REST-Jersey-提供跨站点访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆