Using StringTrimmerEditor with Thymeleaf

Posted at — Jan 25, 2021
Taming Thymeleaf cover
Interested in learning more about Thymeleaf? Check out my book Taming Thymeleaf. The book combines all of my Thymeleaf knowledge into an easy to follow step-by-step guide.

Trimming whitespace is one of the little things that a developer should take care of when coding text inputs in an HTML form. Remembering to do this for each input will get tedious soon, and there is a big chance that you might forget about it sooner or later. Luckily, Spring has the StringTrimmerEditor class that allows to globally configure the trimming once.

To use this in a Spring Boot with Thymeleaf application, we can define an @ControllerAdvice annotated class like this:

import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

public class GlobalControllerAdvice {

    @InitBinder (1)
    public void initBinder(WebDataBinder binder) {
        StringTrimmerEditor stringtrimmer = new StringTrimmerEditor(false); (2)
        binder.registerCustomEditor(String.class, stringtrimmer); (3)
1 Methods annotated with @InitBinder will be called by the Spring framework to initialize the WebDataBinder.
2 Create a StringTrimmerEditor instance. The boolean flag indicates if you want to have an empty string returned as null (use true), or if an empty string should remain an empty string (use false).
3 Register the StringTimmerEditor to the binder for all fields of type String.

Now all excess whitespace will be trimmed automatically when the values are taken from the <input> fields and put in the form data object.

If you want to be notified in the future about new articles, as well as other interesting things I'm working on, join my mailing list!
I send emails quite infrequently, and will never share your email address with anyone else.