我在Play框架中有以下操作:
def action = Action { request =>
common1() // this is common to all the actions
// some functions specific to the action
var json = common2() // this is common to all the actions
Ok(json)
}
我的应用程序中有很多操作。我的问题是在所有操作中都调用了common1
和common2
,我不想重复调用。处理这种情况的好做法是什么?
http filters
如果每个操作都调用了某些内容,则可能需要查看筛选器:https://www.playframework.com/documentation/2.5.x/ScalaHttpFilters
上面链接中的示例:
class LoggingFilter @Inject() (implicit val mat: Materializer, ec: ExecutionContext) extends Filter {
def apply(nextFilter: RequestHeader => Future[Result])
(requestHeader: RequestHeader): Future[Result] = {
val startTime = System.currentTimeMillis
nextFilter(requestHeader).map { result =>
val endTime = System.currentTimeMillis
val requestTime = endTime - startTime
Logger.info(s"${requestHeader.method} ${requestHeader.uri} took ${requestTime}ms and returned ${result.header.status}")
result.withHeaders("Request-Time" -> requestTime.toString)
}
}
}
动作组成:
如果你有一些东西想要为某些操作运行某些代码,请创建你自己的ActionFitlers,ActionRefiners等:https://www.playframework.com/documentation/2.5.x/ScalaActionsComposition
上面链接中的示例:
object LoggingAction extends ActionBuilder[Request] {
def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
Logger.info("Calling action")
block(request)
}
}
用法:
def index = LoggingAction {
Ok("Hello World")
}