Search code examples
javaspringspring-mvcmodelattribute

Spring ModelAttribute correct parsing


I have Spring controller with endpoint like:

@RequestMapping("/provider")
public ResponseEntity<Something> load(@ModelAttribute PageRequest pageRequest)
{
    ... //do something
}

where PageRequest is simple POJO:

class PageRequest 
{
    String[] field;
    String[] value;
    ... // constructor getters settest
} 

When I GET request like: .../provider?field=commanders&value=John%2CBill%2CAlex then pageRequestdata is mapped:

field[0] = commanders;

value[0] = John
value[1] = Bill
value[2] = Alex 

But when I GET request like: .../provider?field=country&value=Australia&field=commanders&value=John%2CBill%2CAlex then pageRequestdata is mapped:

field[0] = country;
field[1] = commanders;

value[0] = Australia
value[1] = "John,Bill,Alex"

My question is why mapping is different for these requests, and can it be done for first request same as for the second. (comma %2C separated data map to single value).

used: Spring 3.x


Solution

  • I did some investigation and figured out that for first request value=John%2CBill%2CAlex Spring using org.springframework.format.supportDefaultFormattingConversionService class which under the hood has org.springframework.core.convert.support.StringToArrayConverter whose convert() method split your string by to array using comma as a separator.

    You have 2 ways to resolve this issue:

    1. Use ; instead of , as separator for you value (value=John;Bill;Alex)
    2. Use different conversion service bean containing your own converter from String to String[]. For more details look at this answer