在Play中使用自定义处理程序覆盖onRouteRequest!斯卡拉 [英] Overriding onRouteRequest with custom handler in Play! scala

查看:68
本文介绍了在Play中使用自定义处理程序覆盖onRouteRequest!斯卡拉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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)
    }
  }
}

该代码是从您所引用的问题移植而来的,该问题针对的是以前的游戏框架版本.

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屋!

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