Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array of one url param

I want get the url-param ids, but It will not work. Is here everyone who can help me? The following code doesn't work.

Url:

http://localhost:9000/rest/alerts?ids[]=123?ids[]=456

Routes.conf

GET /restws/alerts{ids} controllers.AlertService.findAlertsForIds(ids: List[String])

AlertService.java

public static Result findAlertsForIds(List<String> ids){

 return ok("Coole Sache"); 

 }
like image 262
abuder Avatar asked Jun 18 '13 08:06

abuder


2 Answers

This kind of parameter binding works out-of-the box with query-string parameters.

Your route have to be declared like this :

GET /restws/alerts controllers.AlertService.findAlertsForIds(ids: List[String])

And your URL should follow this pattern :

http://localhost:9000/rest/alerts?ids=123&ids=456
like image 85
mguillermin Avatar answered Sep 20 '22 13:09

mguillermin


In short, you've got a lot of options... all a little different from each other. The following URL formats can be used:

  • /foo/bar?color=red&color=blue
  • /foo/bar?color=red,blue
  • /foo/bar?color=[red,blue]
  • /foo/bar?color[]=red,blue

You can either:

1. Use Play Forms

Simple config:

// form definition
case class ColorParams(colors:Seq[String])

val myForm = Form(formMapping(
  "color" -> seq(text(1, 32)))(ColorParams.apply)(ColorParams.unapply)

// in your controller method call
val params = myForm.bindFromRequest()

Example URL: /foo/bar?color[]=red,blue will become List("red","blue")

Sadly this isn't as robust, as many API's use the format color=red,blue or color=red&color=blue

2. Create your own custom query string parser

More elaborate, but you can write constraints, tests, and leave everything to the Router. Pro is that invalid queries never make it to your Controller.

Then you just use it in your Routes file like:

case class ColorParams(colors:List[MyColorEnum])

GET /foo/bar? controllers.Example.getBar(color:ColorParams)

Example URL: /foo/bar?color=red,blue

Because you're parsing the string yourself, you can many any string layout in this post work as desired with this method. See full details on QueryStringBindable. I'll add a full example later.

3. Define your array parameter in the Routes file

GET /foo/bar? controllers.Example.getBar(color:Seq[String])

// inside Example.scala
def getBar( colors:Seq[String] ) = {
    ???
}

Example URL: /foo/bar?color=red&color=blue

Note: I used color in the Routes file, which is the name in the URL, but colors in the getBar method, for clarity. These names don't have to match, just the types.

Gotchas

Note this can be tricky, because /foo/bar?color=red,blue becomes Seq('red,blue'), that is a Seq of one string, not two strings, but it will still display in the debugger as Seq(red,blue). The proper value to see in the debugger would be Seq(red, blue), notice that space? Tricky.

like image 33
Joseph Lust Avatar answered Sep 21 '22 13:09

Joseph Lust