6

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.

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

For a global solution one can merge this answer with the solution from stackoverflow.com/questions/1268021/….

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.