在 Play 中使用自定义处理程序覆盖 onRouteRequest!斯卡拉 [英] Overriding onRouteRequest with custom handler in Play! scala
问题描述
我正在使用 Play 2.2.1 并尝试覆盖 GlobalSettings 中的 onRouteRequest 函数.我在网上找到的所有示例都是在 Play 2.2.x 之前的,它们似乎不适用于 2.2.x.基本上想在所有响应的响应头中设置一些自定义的东西.
I'm using Play 2.2.1 and trying to override the onRouteRequest function in GlobalSettings. All the examples that I found online are for before Play 2.2.x and they don't seem to work in 2.2.x. Basically want to set some custom stuff in the response header for all responses.
到目前为止,我已经尝试了以下基于这个:
So far, I've tried the following, based on this:
object Global extends GlobalSettings {
override def onRouteRequest(request: RequestHeader): Option[Handler] = {
super.onRouteRequest(request).map { handler =>
handler match {
case a: Action[_] => CustomAction(a)
case _ => handler
}
}
}
但是这不起作用,因为没有任何东西与 Action[_] 匹配.
However this doesn't work as nothing matches Action[_].
非常感谢提前提供的所有帮助!
Thanks a lot for all the help in advance!
推荐答案
您需要匹配 EssentialAction
而不是 Action
.这是一个示例,显示了如何为 playframework 2.2 中的每个请求将pragma"标头设置为no-cache"
You need to match on an EssentialAction
instead of Action
. Here is an example which shows how to set the "pragma" header to "no-cache" for every request in playframework 2.2
import play.api._
import play.api.mvc._
import play.api.Play.current
import play.api.http.HeaderNames._
object Global extends GlobalSettings {
def NoCache(action: EssentialAction): EssentialAction = EssentialAction { request =>
action(request).map(_.withHeaders(PRAGMA -> "no-cache"))
}
override def onRouteRequest(request: RequestHeader): Option[Handler] = {
if (Play.isDev) {
super.onRouteRequest(request).map { handler =>
handler match {
case a: EssentialAction => NoCache(a)
case other => other
}
}
} else {
super.onRouteRequest(request)
}
}
}
代码是从您所指的问题中移植过来的,该问题针对的是以前的 playframework 版本.
The code is ported from the question you are refering to which targeted a previous playframework version.
从 playframework 2.1 开始,您还可以使用 doFilter
而不是 onRouteRequest
来实现相同的效果:
Since playframework 2.1 you can also use doFilter
instead of onRouteRequest
to achieve the same:
override def doFilter(action: EssentialAction) = EssentialAction { request =>
if (Play.isDev) {
action(request).map(_.withHeaders(
PRAGMA -> "no-cache"
))
} else {
action(request)
}
}
这篇关于在 Play 中使用自定义处理程序覆盖 onRouteRequest!斯卡拉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!