Home > database >  Spring @PostMapping force null values for formdata urlencode?
Spring @PostMapping force null values for formdata urlencode?

Time:08-11

@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?

CodePudding user response:

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.

  • Related