我开始学习Play,
我一直试图了解Action的实施方式。我只是不理解语言结构而且真的让我感到沮丧.....
我不明白怎么写的?
val echo = Action {request =>好的(“获得请求[”+请求+“]”)}
让它编译......那是什么类型的构造?这将是一个案例类,它将参数作为一个函数,我可能有......
的行动定义其中基本上表明Action是一个函数对象Trait,它通过从Essential动作获取的apply和它自己定义的那个来获取requestHeader或Request ....
/**
* An `EssentialAction` underlies every `Action`. Given a `RequestHeader`, an
* `EssentialAction` consumes the request body (an `Array[Byte]`) and returns
* a `Result`.
*
* An `EssentialAction` is a `Handler`, which means it is one of the objects
* that Play uses to handle requests.
*/
trait EssentialAction extends (RequestHeader => Iteratee[Array[Byte], Result]) with Handler {
/**
* Returns itself, for better support in the routes file.
*
* @return itself
*/
def apply() = this
}
/**
* Helper for creating `EssentialAction`s.
*/
object EssentialAction {
def apply(f: RequestHeader => Iteratee[Array[Byte], Result]): EssentialAction = new EssentialAction {
def apply(rh: RequestHeader) = f(rh)
}
}
/**
* An action is essentially a (Request[A] => Result) function that
* handles a request and generates a result to be sent to the client.
*
* For example,
* {{{
* val echo = Action { request =>
* Ok("Got request [" + request + "]")
* }
* }}}
*
* @tparam A the type of the request body
*/
trait Action[A] extends EssentialAction {
/**
* Type of the request body.
*/
type BODY_CONTENT = A
/**
* Body parser associated with this action.
*
* @see BodyParser
*/
def parser: BodyParser[A]
/**
* Invokes this action.
*
* @param request the incoming HTTP request
* @return the result to be sent to the client
*/
def apply(request: Request[A]): Future[Result]
def apply(rh: RequestHeader): Iteratee[Array[Byte], Result] = parser(rh).mapM {
case Left(r) =>
Play.logger.trace("Got direct result from the BodyParser: " + r)
Future.successful(r)
case Right(a) =>
val request = Request(rh, a)
Play.logger.trace("Invoking action with request: " + request)
Play.maybeApplication.map { app =>
play.utils.Threads.withContextClassLoader(app.classloader) {
apply(request)
}
}.getOrElse {
apply(request)
}
}(executionContext)
我无法自己复制,只有一个简单的例子,它不会编译,这真是太奇怪了....
答案 0 :(得分:2)
您需要注意的是Action
object及其继承的apply
method。
答案 1 :(得分:1)
在scala中,我们可以使用功能块调用Action:
行动{request => .....}
这被改写为:
Action.apply({request => ...})
您可能想知道隐式关键字正在做什么。这是一个 简化使用以使函数的参数可用 功能范围内的隐含范围。换句话说:
行动适用{implicit request => ......}
与:
相同行动申请{request =>隐式val _some_random_name_ =请求 ......}
引自此处:https://groups.google.com/forum/#!topic/scala-user/sR-FD3eiUcQ