Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a list of strings

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?

like image 996
Louth Avatar asked Mar 16 '12 03:03

Louth


People also ask

How do you pass a list to a string in Python?

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.

How do you pass a list to a string in Java?

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.

How do I convert a list of strings to a list of objects?

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 .


1 Answers

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])
like image 63
Julien Richard-Foy Avatar answered Sep 17 '22 12:09

Julien Richard-Foy