在播放scala中传递请求参数

时间:2013-10-25 08:55:37

标签: scala playframework httpwebrequest playframework-2.0 navigationcontroller

我是玩框架(scala)的新手,我仍然通过我的第一个Web应用程序。 我刚刚在我的控制器中创建了第一个方法,索引:

 def index = UserAwareContextAction { implicit request =>
val subset = request.params.get("subset").getOrElse("all")
request.user match {
  case Some(user) => selectIndex(request, subset)
  case _ => Ok(views.html.index())
}

现在我需要弄清楚如何在我的索引请求中实际添加params,我有一个导航scala类:

  val index                     =   GET.on(root).to{Application.index_}

所以我不确定这应该如何相关,在哪里声明请求参数,如何传递它?  我不知道为什么播放文档似乎与我无关。请任何帮助,或有关如何凝视的有用教程,我将非常感激。

2 个答案:

答案 0 :(得分:2)

通常,带参数的播放控制器如下所示:

// Controller
def get(id: Long) = Action { implicit request =>
  // do stuff
  val someArgument = ...
  Ok(views.html.index(someArgument))

// route
GET    /account/:id      AccountController.get(id: Long)

如果您尝试访问查询字符串参数,可以通过简单地调用implicit request

request.queryString访问这些参数

答案 1 :(得分:2)

至少有两种方法。

首先:

你可以让Play为你解析url中的params: 例如,您需要将user_id传递到索引页面,然后您的GET请求的URL可能是这样的:

/index/1

并在播放根文件中:

GET /index/:user_id      Controllers.Application.index(user_id : Int)

所以在这种情况下,Play会根据您的请求网址将user_id解析为1。 或者您的请求可能如下:

/index?user_id=1并在您的根目录中:

GET /index      Controllers.Application.index(user_id : Int) 

再次为你解析它,user_id为1.

在两种情况下,您将此user_id作为控制器中的参数:

def index(user_id : Int) = Action{implicit request =>
       // user_id == 1
       ......
       Ok("")
}

另一个:

直接从控制器中的请求中获取params,例如使用Map作为Request method queryString并且您的控制器可能如下所示:

 def index = Action{ request =>
 // you get your params as Map[String,Seq[String]] where `key` is you parameter `name` and value is //wraped in to a Seq 
    val params = request.queryString
     // or if you want to flatten it to Map[String,Option[String]] for example    
       val params = request.queryString.map {case(k,v) => k->v.headOption}  
       .....    
       Ok("")
        }

对于这种情况,root只是:GET /index Controllers.Application.index