用于在 JAX-RS 服务中设置 HTTP 响应标头的自定义注释

发布于 2024-09-27 01:05:38 字数 775 浏览 4 评论 0原文

我有一个 JAX-RS Web 服务,我想通过新的 CORS 禁用同源策略 HTTP 标头。 (我完全意识到安全隐患。)

我想要一个自定义注释,让我可以设置 HTTP 响应标头。例如,

@ResponseHeaders({"Access-Control-Allow-Origin: *",
                  "Access-Control-Allow-Methods: GET"})
// Or, alternatively:
@AllowOrigins({"*"})
public String resourceMethod() { ... }

这种方法最大限度地减少了样板代码,但我不确定是否存在微妙的技术限制; JAX-RS 提供了许多注释来处理 HTTP 请求,但不处理响应,@Produces 似乎是唯一的例外。

如果可能的话,我也更喜欢远离太多的 web.xml 配置。无需明确需要使用 ResponseBuilder (如果注释使用一个也可以),是否有一种干净的方法来设置自定义 HTTP 响应标头?

为了澄清这一点,我正在寻找与设置 HTTP 响应标头的各种方法集成的注释,以最大限度地减少样板代码。

I have a JAX-RS web service for which I would like to disable the same-origin policy via the new CORS HTTP headers. (I am fully aware of the security implications.)

I'd like to have a custom annotation that lets me set HTTP response headers. For example,

@ResponseHeaders({"Access-Control-Allow-Origin: *",
                  "Access-Control-Allow-Methods: GET"})
// Or, alternatively:
@AllowOrigins({"*"})
public String resourceMethod() { ... }

This approach minimizes boilerplate code, but I'm not sure if there's a subtle technical limitation; JAX-RS provides many annotations to handle the HTTP request but not the response, with @Produces seeming to be the sole exception.

I also prefer to stay away from too much web.xml configuration, if possible. Without explicitly needing to use a ResponseBuilder (it's OK if an annotation uses one), is there a clean way to set custom HTTP response headers?

To clarify, I'm looking for annotations that integrate with the various ways of setting HTTP response headers in order to minimize boilerplate code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅听莫相离 2024-10-04 01:05:38

也许唯一的规范驱动方法是使用自定义 MessageBodyWriter。在 writeTo() 方法中,您将传入一个 MultivaluedMap,您可以在其中设置响应标头。您还会传递所调用的资源方法上的注释(因此您可以获得所需的任何自定义注释)。因此,阅读注释,通过 MultivaluedMap 设置标头,然后使用传入的 OutputStream 写入消息正文。

Apache Wink 和可能的其他 JAX-RS 框架中,您可以创建自定义服务器端处理程序,这些处理程序也可以读取资源方法上的注释并执行您想要的任何操作(例如默认设置响应标头)。

Perhaps the only spec driven approach is to use a custom MessageBodyWriter. In the writeTo() method, you are passed in a MultivaluedMap which you can set response headers on. You are also passed the annotations on the resource method invoked (so you can get whatever custom annotation you want). So read the annotations, set the headers via MultivaluedMap, and then use the OutputStream passed in to write the message body.

In Apache Wink and possibly other JAX-RS frameworks, you can create custom server side handlers that can also read the annotations on the resource method and do whatever you want (like setting response headers by default).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文