To customize request parameter data binding, we can use @InitBinder annotated methods within our controller.

  1. The @InitBinder annotated methods will get called on each HTTP request if we don’t specify the ‘value’ element of this annotation.
  2. Each time this method is called a new instance of WebDataBinder is passed to it.
  3. To be more specific about which objects our InitBinder method applies to, we can supply ‘value’ element of the annotation @InitBinder. The ‘value’ element is a single or multiple names of command/form attributes and/or request parameters that this init-binder method is supposed to apply to.
    @InitBinder("User")
    public void customizeBinding (WebDataBinder binder) 
    {
      .
      .
      .
    }

@Controller
@RequestMapping("/register")
public class UserRegistrationController 
{
    @InitBinder("user")
    public void customizeBinding (WebDataBinder binder) 
    {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
        dateFormatter.setLenient(false);
        binder.registerCustomEditor(Date.class, "dateOfBirth", new CustomDateEditor(dateFormatter, true));
    }
    
    .
    . 
}

simpleDateFormat.setLenient(false); — Will check for out of range Date. For Example, If lenient is set to true, Aug 32 will be converted to Sep 1 .

Comments are closed.