other register

Monday, August 03, 2009

List (array) of parameter values

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:

<input name="key" type="text">
<input name="key" type="text">

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.


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.

class [Ljava.lang.String;

According to, 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:

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:


Also refer to for some useful info regarding [Ljava.lang.String.

No comments: