Sometimes in a web form, it is useful to allow inputting multiple values to be associated with one
In some scenarios, a web form can allow inputting multiple values to be associated with the same named field:
<form>
<input name="key" type="text">
<input name="key" type="text">
</form>
The posted url is like: ?key=value1&key=value2
In Grails, params['key'] is always used to get parameter value. The default behaviour will return:
a string if the key only has one value (i.e. ?key=value)
a List if the key has many values (i.e. ?key=value1&key=value2)
It causes problems when you are not sure how many values the key is associated with.
Solutions:In Java Servlet API, there is a method for Interface ServletRequest
java.lang.String[] request getParameterValues(java.lang.String name)
Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.
request.getParameterValues('key')
class [Ljava.lang.String;
According to
http://groovy.codehaus.org/JN1025-Arrays, we can use the following code to reconstruct the query string:
def queryArray = request.getParameterValues('key')
def queryString = ""
queryArray.each {
queryString += "&key=$it"
}
For the query string like: http://blabla.com/list?personId=1&personId=2
To accommodate this, in Grails scaffolded list closure:
def list = {
def personList
if (params['personId'] != null) {
personList = Person.getAll(Arrays.asList(request.getParameterValues('personId')))
}
else {
personList = Person.list()
}
}
To cast an array into a list, using:
Arrays.asList(array[])
Also refer to
http://prideafrica.blogspot.com/2007/01/javalangclasscastexception.html for some useful info regarding
[Ljava.lang.String.