Spring MVC change default empty string submission to null using @InitBinder

 

Spring by default sets String values to empty strings when populating command from the form object arguments. This default behavior can be changed by registering our default custom editor for String and asking it to set null values to String instead of empty String.

 

Things to remember:

  • The InitBinder is applicable to all the request mappings handled by the controller.
  • Multiple custom Binders can be defined in the Controller.
 
 
Method registering custom editors.
@InitBinder
public void allowEmptyDateBinding( WebDataBinder binder )
{
	    // tell spring to set empty values as null instead of empty string.
	    binder.registerCustomEditor( String.class, new StringTrimmerEditor( true ));  
}
 
 
binder.registerCustomEditor( String.class, new StringTrimmerEditor( true )); -- Will set null to command variable and also trims the String.




binder.registerCustomEditor( String.class, new StringTrimmerEditor( false )); -- Will set "" (empty String) to command 

variable and also trims the string.


 
Sample Controller using @InitBinder:
 
package com.visionjava.employee.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.visionjava.employee.model.Employee;

@Controller
public class EmployeeController {
	@Value("${userName}")
	private String user;
	
	@InitBinder
	public void allowEmptyDateBinding( WebDataBinder binder )
	{
	    // tell spring to set empty values as null instead of empty string.
	    binder.registerCustomEditor( String.class, new StringTrimmerEditor( true ));
	   
	}

	@RequestMapping("/")
	public String showHomePage(){
		System.out.println(user);
		return "employeeHomePage";
	}
	
	@RequestMapping(value="/enroll", method = RequestMethod.GET)
	public ModelAndView showEnrollmentPage(){		
		ModelAndView modelAndView = new ModelAndView("employeeEnrollment");
		modelAndView.addObject("employee", new Employee());
		return modelAndView;
	}
	
	@RequestMapping(value="/submitEnrollment", method = RequestMethod.POST)
	public String submitEnrollment(@Valid @ModelAttribute("employee") Employee employee,
				 BindingResult bindingResult, ModelMap modelMap ){		
		
		if(bindingResult.hasErrors()){
			return "employeeEnrollment";
		}
		
		return "employeeHomePage";
	}
	
}

 
 
 
Web Analytics