Spring MVC 3.1 - How to Convert Form Empty String Values to null Before Controller Execution

If you are using Spring MVC 3.1. Sometime, we want the framework should return the null values for parameters whose values are not set on HTML form. But Spring by default get then as empty strings e.g. "" instead null.

You need to configure @InitBinder inside your controller class. It would do the magic of converting all empty strings to null before passing the form object to controller.

  @InitBinder     /* Converts empty strings into null when a form is submitted */
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}

Comments

Post a Comment