Grails - 为每个响应添加标头
我如何添加一个响应标头 - 比如说 X-Time
,它看起来像:
X-Time: 112
其中给出的值是响应的时间(以毫秒为单位)采取处理?有没有一种非常简单的方法可以将其添加到 Grails 应用程序中?我不想永久保留它,但在开发我的应用程序时保留它会很高兴。
How could I add a response header - say X-Time
that would look something like:
X-Time: 112
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要简单地向响应添加标头,您可以使用
after
过滤器。编辑:
要实际计算时间,使用
javax.servlet.Filter
而不是 Grails 过滤器。src/groovy/com/example/myproject/MyFilter.groovy
src/templates/war/web.xml
(如果 src/templates 尚未在您的源代码树中,请运行 grails install-templates)
使用
javax.servlet.Filter
的原因是您不必分离出“之前”和“之后”操作,因此可以在整个过滤器链和“之后”操作中保留开始时间。 Servlet 执行。补充说明:
对我来说,想要将服务器经过的执行时间作为响应头返回似乎很奇怪。也许你有这样做的充分理由,但在大多数情况下,我会 A)更关心总往返时间(如客户端所观察到的),或者 B)记录服务器上经过的执行时间以供我使用自己的系统管理/指标目的。
To simply add a header to the response, you can use an
after
Filter.Edit:
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
src/templates/war/web.xml
(run grails install-templates if src/templates isn't already in your source tree)
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.Supplementary note:
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.