在Play 2路由中处理自由格式的GET URL参数 [英] Handling freeform GET URL parameters in Play 2 routing

查看:51
本文介绍了在Play 2路由中处理自由格式的GET URL参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个动作,可以选择接受两个参数:

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
}

如何设置我的route文件以使用以下任何调用语法:

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

正确的语法是什么?

推荐答案

类似的方法应该起作用:

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).

如果传递隐式请求并访问getQueryString参数(我认为是Play 2.1.0中添加的),则应该能够访问控制器中的其他可选参数:

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

一个更好的方法可能只是从控制器参数中删除可选名称和年龄,然后从queryString中提取所有内容:

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

更新:2.1版的当前文档 .1对此稍有偏离(自问题#776起已解决),但这是另一个(也是最好的,恕我直言)选项:

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])

然后...

def foo(name: Option[String], age: Option[Int]) = Action { implicit request =>
    Ok(s"Name is: $name, age is $age")
}

这篇关于在Play 2路由中处理自由格式的GET URL参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆