Overriding onRouteRequest with custom handler in Play! scala

情到浓时终转凉″ 提交于 2019-11-29 10:51:14

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.

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) 
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!