Spring Boot + Thymeleaf: Insert a blank form into a NULL string

I have a very simple Spring Boot + Thymeleaf application with one form and pojo as the base model for the form.

The support model has a single-row property, which 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 one input field associated with this 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 a form is submitted, the value will be set to "" (empty string) instead of a null value.

Is there an easy way to get a property to be set to null instead of an empty string?

A running project example can be found at https://github.com/smilingj/springboot-empty-string-to-null .

+4
source share
1 answer

init

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

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/portlet.html#portlet-ann-initbinder

+4

All Articles