How do I intercept all controller requests in Play

2019-03-31 04:10发布

问题:

In the Java flavor of Play 2, there is GlobalSettings.onRequest, which can be used to intercept all incoming requests to controllers. But in the Scala equivalent, there is no onRequest handler.

I suspect this is because the Action delegation logic needed in Java isn't required in Scala, but it's rather annoying because I want to run some code on every incoming controller request.

Does anyone know how to intercept all controller requests in a Scala + Play 2 app?

回答1:

override def onRouteRequest (request: RequestHeader): Option[Handler] in your Global object might be the answer you're looking for.

From the 2.0.4 api, it's called when an HTTP request has been received.



回答2:

You can use action composition. From Play 2.4 docs (https://www.playframework.com/documentation/2.4.x/ScalaActionsComposition):

import play.api.mvc._

object LoggingAction extends ActionBuilder[Request] {
  def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
    Logger.info("Calling action")
    block(request)
  }
}

An then in your controller:

def index = LoggingAction {
  Ok("Hello World")
}

This is what I do when I need to run code for every request. And actually you can control on which requests this is executed by using or not your custom action, as you can still do

def index = Action {
  Ok("Hello World")
}

Hope this helps you.

EDIT

I've just read that you want a 2.0 compliant solution. This is available for Play 2.0, this is the documentation: https://www.playframework.com/documentation/2.0.x/ScalaActionsComposition