Grails - 为每个响应添加标头 [英] Grails - add header to every response

查看:31
本文介绍了Grails - 为每个响应添加标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何添加响应标头 - 比如说 X-Time 看起来像:

How could I add a response header - say X-Time that would look something like:

X 时间:112

给出的值是响应处理所需的时间(以毫秒为单位)?有没有一种非常简单的方法可以将它添加到 Grails 应用程序中?不是我想永久保留的东西,但在开发我的应用程序时会很高兴.

Where the value given would be the time in milliseconds that the response took to process? Is there a really simple way to add this to an Grails app? Not something I want to leave on permanently but would be nice to have while developing my app.

推荐答案

要简单地向响应添加标头,您可以使用 after 过滤器.

To simply add a header to the response, you can use an after Filter.

// grails-app/conf/MyFilters.groovy
class MyFilters {
    def filters = {
        addHeader(uri: '/*') {
            after = {
                response.setHeader('X-Time', value)
            }
        }
    }
}

要实际计算时间,使用 javax.servlet.Filter 而不是 Grails 过滤器.

To actually compute the time, it'd probably be more proper to use a javax.servlet.Filter instead of a Grails filter.

src/groovy/com/example/myproject/MyFilter.groovy

package com.example.myproject

import javax.servlet.*

class MyFilter implements Filter {

    void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {

        def start = System.currentTimeMillis()
        chain.doFilter(request, response)

        def elapsed = System.currentTimeMillis() - start
        response.setHeader('X-Time', elapsed as String)
    }

    void init(FilterConfig config) { }
    void destroy() { }
}

src/templates/war/web.xml(如果源代码树中还没有 src/templates,请运行 grails install-templates)

src/templates/war/web.xml (run grails install-templates if src/templates isn't already in your source tree)

<filter>
  <filter-name>timer</filter-name>
  <filter-class>com.example.myproject.MyFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>timer</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

使用 javax.servlet.Filter 的原因是这样您就不必将之前"和之后"操作分开,因此可以在整个过程中保持开始时间整个过滤器链servlet 执行.

The reason for using the javax.servlet.Filter is so you don't have to separate out your "before" and "after" actions, and can therefore hold onto the start time throughout the entire filter chain & servlet execution.

补充说明:

对我来说,想要将服务器执行时间作为响应头返回似乎很奇怪.也许您有这样做的正当理由,但在大多数情况下,我会 A) 要么更关心总往返时间(如客户端所观察到的那样),要么 B)为我的服务器记录经过的执行时间自己的系统管理/指标目的.

To me, it seems strange to want to return the server elapsed execution time as a response header. Perhaps you have a decent reason for doing it, but in most cases I'd A) either be more concerned about total round-trip time (as observed by the client), or B) be logging elapsed execution times on the server for my own system administration/metrics purposes.

这篇关于Grails - 为每个响应添加标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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