【问题标题】:Overriding onRouteRequest with custom handler in Play! scala在 Play 中使用自定义处理程序覆盖 onRouteRequest!斯卡拉
【发布时间】:2013-12-12 01:21:52
【问题描述】:

我正在使用 Play 2.2.1 并尝试覆盖 GlobalSettings 中的 onRouteRequest 函数。我在网上找到的所有示例都是在 Play 2.2.x 之前的,它们似乎不适用于 2.2.x。基本上想在所有响应的响应头中设置一些自定义的东西。

到目前为止,我已经尝试了以下,基于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[_] 匹配。

非常感谢您提前提供的所有帮助!

【问题讨论】:

    标签: playframework playframework-2.2


    【解决方案1】:

    您需要匹配 EssentialAction 而不是 Action。这是一个示例,展示了如何为 playframework 2.2 中的每个请求将“pragma”标头设置为“no-cache”

    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 版本。

    从 playframework 2.1 开始,您也可以使用 doFilter 而不是 onRouteRequest 来实现相同的效果:

    override def doFilter(action: EssentialAction) = EssentialAction { request =>
      if (Play.isDev) {
        action(request).map(_.withHeaders(
          PRAGMA -> "no-cache"
        ))
      } else {
        action(request) 
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 1970-01-01
      • 2012-11-15
      • 1970-01-01
      相关资源
      最近更新 更多