【问题标题】:Get HTTP Response size from Grails plugin从 Grails 插件获取 HTTP 响应大小
【发布时间】:2013-03-21 13:31:21
【问题描述】:

我正在尝试编写一个 Grails 插件,用于记录安装它的应用程序发送的每个 HTTP 响应的大小。到目前为止我尝试过的方法是:

(1) 编写一个包裹response 的servlet 过滤器。响应包装器用计算响应中字节数的OutputStream 装饰OutputStream。这些类显示为here

(2)在插件描述符中注册servlet过滤器

def doWithWebDescriptor = { webXml ->

    def contextParam = webXml.'context-param'

    contextParam[contextParam.size() - 1] + {
        'filter' {
            'filter-name'('countingFilter')
            'filter-class'(CountingFilter.name)
        }
    }

    def filter = webXml.'filter'
    filter[filter.size() - 1] + {
        'filter-mapping' {
            'filter-name'('countingFilter')
            'url-pattern'('/*')
        }
    }
}

(3) 在 Grails 过滤器中,尝试检索写入的字节数,如下所示:

afterView = {
    // countingFilter registers the response wrapper as an attribute of the request
    // named 'counter'
    request.getAttribute('counter').byteCount
}

但总是返回值 0。但是,我发现如果我将上面的代码添加到 Grails 过滤器的 afterafterView 闭包中

after = {
    // returns 0
    request.getAttribute('counter').byteCount
}

afterView = {
    // returns the correct response size
    request.getAttribute('counter').byteCount
}

它现在返回正确的响应大小,但似乎站点网格布局生成的内容已经消失,只剩下 GSP 本身中的内容。

看来我已经接近解决方案了。我的猜测是我在错误的时间刷新缓冲区,和/或我的过滤器没有在过滤器链中的正确点运行。

事实证明,这比我预期的要困难得多。有没有更简单的方法?

【问题讨论】:

    标签: grails servlet-filters


    【解决方案1】:

    Grails 内置了这个功能。它没有被记录。通过将“-DGSPResponseWriter.enableContentLength=true”选项添加到 JVM 参数,将系统属性“GSPResponseWriter.enableContentLength”设置为 true。有关详细信息,请参阅source code of GSPResponseWriter

    默认不启用的原因是计算内容长度并不简单,因为某些字符在 UTF-8 编码中是多字节的。 BoundedCharsAsEncodedBytesCounter 是进行计算的类。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-13
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多