Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling freeform GET URL parameters in Play 2 routing

Let's say I have an action that optionally accepts two parameters:

def foo(name: String, age: Integer) = Action { 
  // name & age can both be null if not passed
}

How do I setup my route file to work with any of the following call syntaxes:

/foo
/foo?name=john
/foo?age=18
/foo?name=john&age=18
/foo?authCode=bar&name=john&age=18    // The controller may have other implicit parameters

What is the correct syntax for this?

like image 786
ripper234 Avatar asked Apr 30 '13 13:04

ripper234


1 Answers

Something like this should work:

GET  /foo         controllers.MyController.foo(name: String ?= "", age: Int ?= 0)

Since your parameters can be left off you need to provide default values for them (and handle those values in the controller function).

You should be able to access other optional parameters in the controller if you pass in an implicit request and access the getQueryString parameter (added in Play 2.1.0 I think):

def foo(name: String, age: Integer) = Action { implicit request =>
   val authCode: Option[String] = request.getQueryString("authCode")
   ...
}

A nicer way to do it might just be to take your optional name and age out of the controller parameters and extract everything from the queryString:

def foo = Action { implicit request =>
    val nameOpt: Option[String] = request.getQueryString("name")
    val ageOpt: Option[String] = request.getQueryString("age")
    ...
}

Update: The current docs for 2.1.1 are a bit off about this (since fixed with issue #776) but this is another (and the best, IMHO) option:

GET  /foo    controllers.MyController.foo(name: Option[String], age: Option[Int])

And...

def foo(name: Option[String], age: Option[Int]) = Action { implicit request =>
    Ok(s"Name is: $name, age is $age")
}
like image 89
Mikesname Avatar answered Nov 20 '22 08:11

Mikesname