I'm learning myself Play 2.0 (Java API used) and would like to have a double/float parameter (for location coordinates), something like http://myfooapp.com/events/find?latitude=25.123456&longitude=60.251253.
I can do this by getting the parameters as String and parsing them at controller etc but can I use automatic binding here?
Now, I first tried simply having one double value:
GET /events/foo controllers.Application.foo(doublevalue: Double)
with
public static Result foo(Double doublevalue) {
return ok(index.render("Foo:" + doublevalue));
}
What I got was "No QueryString binder found for type Double. Try to implement an implicit QueryStringBindable for this type."
Have I missed something already provided or do I have to make a custom QueryStringBindable that parses Double?
I found some instructions on making a custom string query string binder with Scala at http://julien.richard-foy.fr/blog/2012/04/09/how-to-implement-a-custom-pathbindable-with-play-2/
I implemented DoubleBinder at package binders:
import java.util.Map;
import play.libs.F.Option;
import play.mvc.QueryStringBindable;
public class DoubleBinder implements QueryStringBindable<Double>{
@Override
public Option<Double> bind(String key, Map<String, String[]> data) {
String[] value = data.get(key);
if(value == null || value.length == 0) {
return Option.None();
} else {
return Option.Some(Double.parseDouble(value[0]));
}
}
@Override
public String javascriptUnbind() {
// TODO Auto-generated method stub
return null;
}
@Override
public String unbind(String key) {
// TODO Auto-generated method stub
return null;
}
}
And tried to add it to project/Build.scala's main:
routesImport += "binders._"
but same result : "No QueryString binder found for type Double...."
Currently (in Play 2.0), Java binders only work with self-recursive types. That is, types looking like the following:
class Foo extends QueryStringBindable<Foo> {
…
}
So, if you want to define a binder for java.lang.Double
, which is an existing type of Java, you need to wrap it in a self-recursive type. For example:
package util;
public class DoubleW implements QueryStringBindable<DoubleW> {
public Double value = null;
@Override
public Option<DoubleW> bind(String key, Map<String, String[]> data) {
String[] vs = data.get(key);
if (vs != null && vs.length > 0) {
String v = vs[0];
value = Double.parseDouble(v);
return F.Some(this);
}
return F.None();
}
@Override
public String unbind(String key) {
return key + "=" + value;
}
@Override
public String javascriptUnbind() {
return value.toString();
}
}
Then you can use it as follows in your application:
GET /foo controllers.Application.action(d: util.DoubleW)
public static Result action(DoubleW d) {
…
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With