2012-06-26 35 views

Trả lời

5

đây bạn đã có mẫu tốt như thế nào nó được thực hiện trong Play:

https://github.com/playframework/Play20/blob/master/samples/scala/zentasks/app/controllers/Application.scala

val loginForm = Form(
    tuple(
    "email" -> text, 
    "password" -> text 
) verifying ("Invalid email or password", result => result match { 
    case (email, password) => User.authenticate(email, password).isDefined 
    }) 
) 



/** 
* Handle login form submission. 
*/ 
def authenticate = Action { implicit request => 
    loginForm.bindFromRequest.fold(
    formWithErrors => BadRequest(html.login(formWithErrors)), 
    user => Redirect(routes.Projects.index).withSession("email" -> user._1) 
) 
} 

Nó được mô tả trong tài liệu của forms submission

2

như @Marcus chỉ ra, bindFromRequest là cách tiếp cận ưa thích. Đối với trường hợp đơn giản một lần, tuy nhiên, một lĩnh vực

<input name="foo" type="text" value="1"> 

có thể được truy cập thông qua hình thức post'd như vậy

val test = Action { implicit request => 
    val maybeFoo = request.body.get("foo") // returns an Option[String] 
    maybeFoo map {_.toInt} getOrElse 0 
} 
+11

'Lỗi biên dịch [giá trị nhận không phải là thành viên của play.api.mvc.AnyContent]'? – Meekohi

+1

Hãy thử 'request.body.asFormUrlEncoded.get (" foo "). Lift (0)' - Tôi dường như nhận được một 'ArrayBuffer' và' lift (0) 'trả về một' Option' của phần tử nó chứa – Techmag

8

Như Play 2.1, có hai cách để có được thông số POST:

1) Tuyên bố của cơ thể như form-urlencoded qua một tham số hành động phân tích cú pháp, trong trường hợp này request.body được tự động chuyển đổi thành một bản đồ [string, Seq [Chuỗi]]:

def test = Action(parse.tolerantFormUrlEncoded) { request => 
    val paramVal = request.body.get("param").map(_.head) 
} 

2) Bằng cách gọi request.body.asFormUrlEncoded để có được bản đồ [String, Seq [Chuỗi]]:

def test = Action { request => 
    val paramVal = request.body.asFormUrlEncoded.get("param").map(_.head) 
} 
0

đây bạn đã có mẫu tốt như thế nào nó được thực hiện trong Chơi 2:

def test = Action(parse.tolerantFormUrlEncoded) { request => 
 
    val paramVal = request.body.get("param").map(_.head).getorElse(""); 
 
}

Các vấn đề liên quan