Using play framework 2.0 in Java mode and I want to pass a list of strings to a Controller using the URL parameters.
Given a URL such as:
http://localhost:9000/echo?messages=hello&messages=world
I want to call my Controller method:
public static Result echo(List<String> messages){
return ok("Size: " + messages.size());
}
My routes file looks like this:
GET /echo controllers.Application.echo(messages: List[String])
But it doesn't work. I get errors claiming there is no QueryString binder for List[String]. This doesn't seem right to me as this was pretty standard functionality in the previous version. Does anybody know how I can pass a list of strings to the controller using a Java project?
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
We can use the toArray(T[]) method to copy the list into a newly allocated string array. We can either pass a string array as an argument to the toArray() method or pass an empty string type array. If an empty array is passed, JVM will allocate memory for the string array.
Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList); Any Collection can be passed as an argument to the constructor as long as its type extends the type of the ArrayList , as String extends Object .
For now you can retrieve them from the query string:
public static Result echo(){
String[] messages = request().queryString().get("messages");
return ok("Size: " + messages.length);
}
Update: A list binder has been added, so you can just write the following:
public static Result echo(List<String> messages) {
return ok("Size:" + messages.size());
}
Be sure your route definition looks like the following:
GET /echo controllers.Application.echo(messages: java.util.List[String])
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