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

查看:65
本文介绍了如何在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中处理请求参数的绑定和解释,特别是考虑到这两个参数都应该是可选的.

这些参数应该以某种方式在路线"规范中表示吗?另外,响应的Controller方法是否应该以某种方式从请求对象中分离参数?还有另一种方法吗?

解决方案

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

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

并声明以下路线:

GET   /birthday       controllers.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天全站免登陆