Skip to content

Spring @PostMapping force null values for formdata urlencode?

public class TestController {
    public void test(TestFilter test) {
       System.out.println( != 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?



Could solve it as follows:

public class StringTrimAdvice {
    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