在Play中调用常用功能

时间:2016-06-12 13:20:59

标签: scala playframework playframework-2.0

我在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)
  }

我的申请中有很多动作。我的问题是在所有操作中调用common1common2,我不想重复调用。处理这种情况会有什么好处?

1 个答案:

答案 0 :(得分:1)

Http过滤器

如果每次操作都调用了某些内容,您可能需要查看过滤器: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")
}