Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access post data from scala play?

I have a route that is type "POST". I am sending post data to the page. How do I access that post data. For example, in PHP you use $_POST

How do I access the post data in scala and play framework?

like image 285
user1435853 Avatar asked Jun 26 '12 16:06

user1435853


3 Answers

As of Play 2.1, there are two ways to get at POST parameters:

1) Declaring the body as form-urlencoded via an Action parser parameter, in which case the request.body is automatically converted into a Map[String, Seq[String]]:

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

2) By calling request.body.asFormUrlEncoded to get the Map[String, Seq[String]]:

def test = Action { request =>
    val paramVal = request.body.asFormUrlEncoded.get("param").map(_.head)
}
like image 182
Leonya Avatar answered Sep 20 '22 15:09

Leonya


Here you've got good sample how it's done in 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)
  )
}

It's described in the documentation of the forms submission

like image 41
biesior Avatar answered Sep 22 '22 15:09

biesior


as @Marcus points out, bindFromRequest is the preferred approach. For simple one-off cases, however, a field

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

can be accessed via post'd form like so

val test = Action { implicit request =>
  val maybeFoo = request.body.get("foo") // returns an Option[String]
  maybeFoo map {_.toInt} getOrElse 0
}
like image 40
virtualeyes Avatar answered Sep 21 '22 15:09

virtualeyes