Bind empty String as null in Spring Boot
When a form is submitted with an input field without any data, the browser submits it as an empty string ""
. That's why Spring Boot writes this to the data object exactly this way - with a StringTrimmerEditor
configuration in place, we can bind the value as null
instead.
@ControllerAdvice
public class ControllerConfig {
@InitBinder
void initBinder(final WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
}
▴ Configuration to convert empty Strings to null
The above ControllerAdvice
adds a new editor to our WebDataBinder
. StringTrimmerEditor
first removes all spaces at the beginning and end of the submitted form data (trim) - this is usually just an incorrect input from the user. With the parameter true
empty Strings will also be converted to null
.
This saves us from handling different cases separately and allows us to persist the data directly into the database, where we prefer to store a null
value when no information was provided.
Bootify is a tool to intialize Spring Boot applications with its own database schema, an optional Thymeleaf frontend with CRUD functionalities and many more features on top - online in the browser without registration. When a frontend is selected, the StringTrimmerEditor
is also provided exactly as described above.
Subscribe to my newsletter
Read articles from Thomas Surmann directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by