如何在RESTEasy中启用JSONP? [英] How enable JSONP in RESTEasy?

查看:126
本文介绍了如何在RESTEasy中启用JSONP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题说我的问题。我需要将DTO包装到javascript方法回调中。目前我按要求返回JSON。但是在Ajax中使用它的问题是因为我将GET发送到其他域。当然还有安全警察。

Title say about my issue. I need wrap DTO in to a javascript method callback. Currently I return on request JSON. But problem with using this in Ajax because I send GET to other domain. and of course security police.

我有创意添加提供。你有任何例子,链接或建议如何做到这一点。

I have idea to create addition provide. Have you any example, links or suggestion how can do this.

推荐答案

在RESTEasy中没有明确的JSONP支持,但是一个简单的在你的应用程序中启用JSONP的方法是编写一个Servlet过滤器。

There's no explicit support for JSONP in RESTEasy, however one easy way to enable JSONP in your application is to write a Servlet Filter.

这里有一些链接可以帮助你编写一个过滤器:

Here's a few links that can help you write a filter:

从JAX-RS Web服务提供JSONP

使用Spring的DelegatingFilterProxy实现JSONP回调的Servlet过滤器(如果您正在使用春天)

Implementing a Servlet Filter for JSONP callback with Spring’s DelegatingFilterProxy (if you're using Spring)

当我有这个要求时,我最终写了自己的,因为我找到的所有例子似乎都没有给办了。以下是我编写自己的过滤器的建议:

When I had this requirement I ended up writing my own since none of the examples I found seemed to quite nail it. Here's my advice for writing your own filter:


  • 如果指定了回调参数(显然),则只包装响应

  • only wrap the response if a callback parameter is specified (obviously)

如果响应内容类型为 application / json ,则仅包装响应(或者如果您想支持更广泛的选择变体,仅在响应内容类型为 application / json application / * + json )时才进行换行

only wrap the response if the response content type is application/json (or if you want to support a wider selection of variants, only wrap if the response content type is application/json or application/*+json)

使用HttpServletResponseWrapper,以便您可以调用前向链( chain.doFilter )而无需写入任何数据真实的回应。完成前向链后,您可以检查内容类型,确保要将响应包装为JSONP,然后将捕获的数据与JSONP前缀和后缀一起写入真实响应。

use an HttpServletResponseWrapper so that you can invoke the forward chain (chain.doFilter) without writing any data to the real response. Once the forward chain is complete you can then check the content type, make sure you want to wrap the response as JSONP, then write the captured data into the real response, along with the JSONP prefix and suffix.

当您决定将响应包装为JSONP时,请确保将响应内容类型更改为 text / javascript

when you do decide to wrap the response as JSONP, make sure you change the response content type to text/javascript

如果您之前没有做过多次使用Java EE过滤器,您可能需要阅读首先是Java EE教程的相关部分:过滤请求和响应

If you haven't done much with Java EE Filters before, you may want to read the relevant section of the Java EE tutorial first: Filtering Requests and Responses.

这篇关于如何在RESTEasy中启用JSONP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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