如何为 Grails 中所有控制器的所有操作添加自定义响应标头

问题描述 投票:0回答:1

环境:

  • Grails:5.3.3(或 Grails 6.x)
  • Java:OpenJDK 11

我需要添加标头来响应所有控制器的所有操作。 我尝试实现如下拦截器:

Cors拦截器:

 class CorsInterceptor {
      CorsInterceptor() {
            matchAll()
            log.info("CorsInterceptor(): BEGIN ")

      }
      boolean before() {
            log.info("before(): BEGIN")
            true }

      boolean after() {
            response.addHeader("MyRespHeader","My dream data here")
            log.info("after(): final")
            true
      }

      void afterView() {
            log.info("afterView(): BEGIN ...")
            response.setHeader("MyRespHeader","My dream data here")
        // no-op
      }

}

日志输出:

2024-04-07 19:55:04.287  INFO --- [tp1902630939-52] com.example.CorsInterceptor              : before(): BEGIN
2024-04-07 19:55:04.312  INFO --- [tp1902630939-52] com.example.HomeController               : json:{
   "fieldname": "city",
   "value": "Tokyo city"
}
2024-04-07 19:55:04.319  INFO --- [tp1902630939-52] com.example.CorsInterceptor              : after(): final
2024-04-07 19:55:04.319  INFO --- [tp1902630939-52] com.example.CorsInterceptor              : afterView(): BEGIN ...

从log的输出中我可以确定

after()
CorsInterceptor
已经被执行了。但是,从邮递员那里,我没有找到自定义响应标头
MyRespHeader

我知道我可以添加:

response.addHeader("MyRespHeader","My dream data here")

每个控制器的每个动作都会起作用!但这不是一个好方法。

我的代码在这里:https://github.com/wureka/g612-demo

如有任何建议,我们将不胜感激。

grails
1个回答
0
投票

使用控制器中的

ResponseRenderer.render(CharSequence txt)
方法,刷新
ServletResponse
的编写器,然后将响应设置为已提交。这意味着响应的状态代码已设置,其标头已写入并且无法再更改。

这就是为什么在

CorsInterceptor.after()
方法中添加 header 没有效果。

但是,您可以在

CorsInterceptor.before()
方法中设置标题。

© www.soinside.com 2019 - 2024. All rights reserved.