17

我有一条类型为“POST”的路线。我正在向页面发送帖子数据。我如何访问该帖子数据。例如,在 PHP 中,您使用 $_POST

如何访问 scala 和 play 框架中的帖子数据?

4

4 回答 4

9

从 Play 2.1 开始,有两种方法可以获取 POST 参数:

1) 通过 Action 解析器参数将 body 声明为 form-urlencoded,在这种情况下 request.body 会自动转换为 Map[String, Seq[String]]:

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

2)通过调用request.body.asFormUrlEncoded获取Map[String, Seq[String]]:

def test = Action { request =>
    val paramVal = request.body.asFormUrlEncoded.get("param").map(_.head)
}
于 2013-10-07T18:41:28.690 回答
5

在这里,您有很好的示例如何在 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)
  )
}

它在表单提交的文档中有所描述

于 2012-06-26T23:16:51.557 回答
2

正如@Marcus 指出的那样, bindFromRequest 是首选方法。然而,对于简单的一次性情况,一个字段

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

可以通过 post'd 表单访问,如下所示

val test = Action { implicit request =>
  val maybeFoo = request.body.get("foo") // returns an Option[String]
  maybeFoo map {_.toInt} getOrElse 0
}
于 2012-06-27T02:06:56.953 回答
0

在这里,您有很好的示例如何在 Play 2 中完成:

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

于 2017-06-20T05:18:57.473 回答