I have a very simple Spring Boot + Thymeleaf application with a single form and a pojo as backing model for the form.
The backing model has a single string property that is null by default:
public class Model {
private String text = null;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public String toString() {
return "Model [text=" + (text == null ? "<null>" : text.isEmpty() ? "<empty>" : text) + "]";
}
}
The form has a single input field bound to that property:
<form action="#" th:action="@{/}" th:object="${model}" method="post">
<label th:for="${#ids.next('text')}">Text</label>
<input type="text" th:field="*{text}" />
<button type="submit">Submit</button>
</form>
However whenever the form is submitted the value will be set to "" (empty string) instead of a null value.
Is there a simple way to achieve that the property will be set to null instead of an empty string?
The running sample project can be found at https://github.com/smilingj/springboot-empty-string-to-null.
Add an initbinder to your controller
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
Refer the offcial reference
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/portlet.html#portlet-ann-initbinder
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With