如何在 Play 框架中处理可选的查询参数 [英] How to handle optional query parameters in Play framework

查看:22
本文介绍了如何在 Play 框架中处理可选的查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 Scala 中有一个已经运行的基于 Play 2.0 框架的应用程序,它提供一个 URL,例如:

http://localhost:9000/birthdays

回复所有已知生日的列表

我现在想通过添加使用可选的from"(日期)和to"请求参数来限制结果的能力来增强这一点,例如

http://localhost:9000/birthdays?from=20120131&to=20120229>

(此处的日期解释为 yyyyMMdd)

我的问题是如何使用 Scala 处理 Play 2.0 中的请求参数绑定和解释,特别是考虑到这两个参数都应该是可选的.

这些参数应该在路由"规范中以某种方式表达吗?或者,响应控制器方法是否应该以某种方式从请求对象中挑选参数?还有其他方法可以做到这一点吗?

解决方案

将可选参数编​​码为 Option[String](或 Option[java.util.Date],但您必须实现自己的 QueryStringBindable[Date]):

defbirths(from: Option[String], to: Option[String]) = Action {//...}

并声明以下路线:

GET/birthday controller.Application.birthday(from: Option[String], to: Option[String])

Lets say I have an already functioning Play 2.0 framework based application in Scala that serves a URL such as:

http://localhost:9000/birthdays

which responds with a listing of all known birthdays

I now want to enhance this by adding the ability to restrict results with optional "from" (date) and "to" request params such as

http://localhost:9000/birthdays?from=20120131&to=20120229

(dates here interpreted as yyyyMMdd)

My question is how to handle the request param binding and interpretation in Play 2.0 with Scala, especially given that both of these params should be optional.

Should these parameters be somehow expressed in the "routes" specification? Alternatively, should the responding Controller method pick apart the params from the request object somehow? Is there another way to do this?

解决方案

Encode your optional parameters as Option[String] (or Option[java.util.Date], but you’ll have to implement your own QueryStringBindable[Date]):

def birthdays(from: Option[String], to: Option[String]) = Action {
  // …
}

And declare the following route:

GET   /birthday       controllers.Application.birthday(from: Option[String], to: Option[String])

这篇关于如何在 Play 框架中处理可选的查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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