0

I'm using Grails 2.3.7 and have a controller method which binds the request to a command class. One of the fields in the command class is a String array, as it expects multiple params with the same name to be specified - e.g. ?foo=1&foo=2&foo=3&bar=0.

This works fine most of the time. The one case where it fails is if the param value contains a comma - e.g. ?foo=val1,val2&foo=val3,val4. In this case I'm getting an array with 4 values: ["val1","val2","val3","val4"], not the intended output of ["val1,val2","val1,val2"]. URL escaping/encoding the comma does not help and in my cases the param value is surrounded by quote characters as well (foo=%22a+string+with+commas,+etc%22).

I had a similar problem with Spring 3.x which I was able to solve: How to prevent parameter binding from interpreting commas in Spring 3.0.5?. I've attempted one of the answers by adding the following method to my controller:

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(String[].class, new StringArrayPropertyEditor(null));
}

However this didn't work.

I also tried specifying a custom conversion service, based on the comment in https://jira.grails.org/browse/GRAILS-8997.

Config/spring/resources.groovy:

beans = {
    conversionService (org.springframework.context.support.ConversionServiceFactoryBean) {
        converters = [new CustomStringToArrayConverter()]
    }
}

and

import org.springframework.core.convert.converter.Converter
import org.springframework.util.StringUtils

class CustomStringToArrayConverter implements Converter<String, String[]> {
    @Override
    public String[] convert(String source) {
        return StringUtils.delimitedListToStringArray(source, ";");
    }
}

but I couldn't get this to work either.

Community
  • 1
  • 1
nickdos
  • 8,348
  • 5
  • 30
  • 47

1 Answers1

0

For now, I've come up with a work around. My Controller method has an extra line to set the troublesome field explicitly with:

commandObj.foo = params.list('foo') as String[]

I'm still open to suggestions on how to configure grails to not split on a comma...

nickdos
  • 8,348
  • 5
  • 30
  • 47