Skip to content
Advertisement

Spring @PostMapping force null values for formdata urlencode?

@RestController
public class TestController {
    @PostMapping("/test")
    public void test(TestFilter test) {
       System.out.println(test.id != null);         //true
       System.out.println(test.origin == null);      //false
       System.out.println(test.destination == null); //false
    }
}

public class TestFilter {
    public String id;
    public String origin;
    public String destination;
}

When I run the following request, the values in my received object are not null, but "" empty:

curl --location --request POST 'localhost:8080/test' 
--header 'Content-Type: application/x-www-form-urlencoded' 
--data-urlencode 'id=1' 
--data-urlencode 'origin=' 
--data-urlencode 'destination='

Question: how can I tell Spring to not add empty values on Strings, but keep them null?

Advertisement

Answer

Could solve it as follows:

@ControllerAdvice
public class StringTrimAdvice {
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
}

This converts any empty strings to nulls.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement