Handling freeform GET URL parameters in Play 2 routing

↘锁芯ラ 提交于 2019-11-30 13:02:55

问题


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?


回答1:


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")
}


来源:https://stackoverflow.com/questions/16301211/handling-freeform-get-url-parameters-in-play-2-routing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!