2014-01-30 71 views
3

在播放框架(階)文檔(http://www.playframework.com/documentation/2.2.x/ScalaActions)它說:play.api.mvc.Action實際如何返回結果?

甲play.api.mvc.Action基本上是一個(play.api.mvc.Request => play.api.mvc.Result )函數處理請求並生成要發送給客戶端的結果。

val echo = Action { request => 
    Ok("Got request [" + request + "]") 
} 

一個動作返回一個play.api.mvc.Result值,表示要發送到Web客戶端的HTTP響應。在這個例子中,Ok構造了一個包含文本/純文本響應主體的200 OK響應。

現在,當我創建了回聲VAL(如上),在控制檯上作爲建議我沒有得到一個結果值,而是一個行動[AnyContent]

scala> play.api.mvc.Action[play.api.mvc.AnyContent] = Action(parser=BodyParser(anyContent)) 

這到底是怎麼回事?文檔中是否有錯誤?

+4

@vptheron我想是因爲我沒有完全理解語言的主要概念,但我不能從不同的角度解決這個問題。 Jeeez,當你知道**時,它總是顯而易見的。當你甚至不知道正確的問題時,基本上就像在黑暗中摸索。我想你已經知道了Scala語言,然後出來了你母親的子宮嗎?給我一個休息時間。我試圖讓我的腦海裏浮現一些對我來說很陌生的複雜而抽象的概念。 – Zuriar

回答

4

事實上,如果你看看Action代碼:https://github.com/playframework/playframework/blob/master/framework/src/play/src/main/scala/play/api/mvc/Action.scala

val echo = Action { request => 
    Ok("Got request [" + request + "]") 
} 

這需要的Actionapply方法確實返回一個新Action

/** 
* Constructs an `Action` with default content. 
* 
* For example: 
* {{{ 
* val echo = Action { request => 
* Ok("Got request [" + request + "]") 
* } 
* }}} 
* 
* @param block the action code 
* @return an action 
*/ 
final def apply(block: R[AnyContent] => Result): Action[AnyContent] = 
    apply(BodyParsers.parse.anyContent)(block) 

然後:

/** 
* Constructs an `Action`. 
* 
* For example: 
* {{{ 
* val echo = Action(parse.anyContent) { request => 
* Ok("Got request [" + request + "]") 
* } 
* }}} 
* 
* @tparam A the type of the request body 
* @param bodyParser the `BodyParser` to use to parse the request body 
* @param block the action code 
* @return an action 
*/ 
final def apply[A](bodyParser: BodyParser[A])(block: R[A] => Result): Action[A] = 
    async(bodyParser) { req: R[A] => 
    block(req) match { 
     case simple: SimpleResult => Future.successful(simple) 
     case async: AsyncResult => async.unflatten 
    } 
} 

I ñ事實上,後來,該框架將調用的其他apply方法Action你通過傳遞Request參數創建:

/** 
* Invokes this action. 
* 
* @param request the incoming HTTP request 
* @return the result to be sent to the client 
*/ 
def apply(request: Request[A]): Future[SimpleResult] 

例如:

echo(request) 

這種方法,然後返回一個Result,您之前在

val echo = Action { request => 
    Ok("Got request [" + request + "]") 
} 

我希望我已經夠清楚了!