Is there an easy way to turn empty form inputs into null strings in Spring MVC?

Perhaps you can use a custom Binder


I know this is old, but I wasted about 2 or 3 hours until I found a very easy way to apply a StringTrimmerEditor with a binder for all my controllers.

Once again: I must remember to RTFM.

In spring 3.2 you can create a @ControllerAdvice-annottated controller class and use the @InitBinder-annotated method just like the example @Affe gave.

http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-initbinder-advice

Here is an example:

@ControllerAdvice
@Controller
public class AppBindingInitializer {

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

}

Hope it helps someone.


The class you're looking for is:

org.springframework.beans.propertyeditors.StringTrimmerEditor

If you construct it with a true it will convert empty/whitespace strings to null. How to get it registered onto the binder depends on if you want it to be the default or only apply to certain views.

e.g., on a single controller you can just add

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

instructions here