Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

playframework - Overriding onRouteRequest with custom handler in Play! scala

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
      }
    }
  }

However this doesn't work as nothing matches Action[_].

Thanks a lot for all the help in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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) 
? }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...