Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot + Thymeleaf: Bind empty form input to NULL-string

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.

like image 343
Johannes Grimm Avatar asked May 25 '15 11:05

Johannes Grimm


1 Answers

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

like image 120
Faraj Farook Avatar answered Oct 04 '22 06:10

Faraj Farook