Home > OS >  Spring RestController not splitting RequestParam Set<String> provided by comma syntax if Set&l
Spring RestController not splitting RequestParam Set<String> provided by comma syntax if Set&l

Time:12-28

I have an endpoint that accepts Set as RequestParam.

@ResponseStatus(OK)
@GetMapping(value = "/people")
public PeopleResponse getPeople(@RequestParam(name = "idType2") Set<String> idsType1) {
    return service.getPeople(idsType1);
}

and this works fine with both types of collection requestparam assignments resulting in 3 elements inside the set.

localhost:8080/foo/bar/people?idsType1=QWE,RTY,UIO
localhost:8080/foo/bar/people?idsType1=QWE&idsType1=RTY,&idsType1=UIO

However if I move the set into a wrapping class

@Value
@RequiredArgsConstructor
public class IdsType1 {
    Set<String> idsType1;     
}

@ResponseStatus(OK) @GetMapping(value = "/people") public PeopleResponse getPeople( @Valid IdsType1 idsType1) { (...)

The comma separated collection ends up being one element containing "QWE,RTY,UIO". The other type of assignment still works fine.

The reason why I wrap my set is because I actually have more parameters and I need to do a complex validation using custom validator. The code above is however the simplest code that unearths the problem that I'm having.

SpringBoot 2.2.1-RELEASE Java 8 openjdk

CodePudding user response:

The solution for me was to upgrade the SpringBoot version to 2.5.0 (2.3.X still had this issue, I haven't tried 2.4.X). The collection is correctly assigned in this version.

I'm aware that not everyone can simply upgrade their SpringBoot version in their project. If you are in such situation, then the next place I would look at for possible solution would be Converters DataBinders etc. My assumption is that StringToCollectionConverter is not triggered because technically there is a conversion to an object, not a collection.

https://docs.spring.io/spring-framework/docs/4.0.x/spring-framework-reference/html/validation.html

https://www.baeldung.com/spring-mvc-custom-data-binder

https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-typeconversion

  • Related