How do I intercept all controller requests in Play

2019-03-31 03:54发布

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?

2条回答
干净又极端
2楼-- · 2019-03-31 04:16

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.

查看更多
3楼-- · 2019-03-31 04:29

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

查看更多
登录 后发表回答