@Controller
public class MyFormController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
// ...
}
Method Parameters And Type Conversion
type of the method parameter or field (e.g., binding a request parameter to a field in
an @ModelAttribute parameter) they’re bound to. If the target type is not String,
Spring automatically converts to the appropriate type. All simple types such as int,
long, Date, etc. are supported. You can further customize the conversion process through
a WebDataBinder (see Customizing WebDataBinder initialization) or by registering Formatters with
the FormattingConversionService (see [format]).
Customizing WebDataBinder initialization
To customize request parameter binding with PropertyEditors through Spring’s
WebDataBinder, you can use @InitBinder-annotated methods within your controller,
@InitBinder methods within an @ControllerAdvice class, or provide a custom
WebBindingInitializer. See the [mvc-ann-controller-advice] section for more details.
Customizing data binding with @InitBinder
Annotating controller methods with @InitBinder allows you to configure web data
binding directly within your controller class. @InitBinder identifies methods that
initialize the WebDataBinder that will be used to populate command and form object
arguments of annotated handler methods.
Such init-binder methods support all arguments that @RequestMapping methods support,
except for command/form objects and corresponding validation result objects. Init-binder
methods must not have a return value. Thus, they are usually declared as void.
Typical arguments include WebDataBinder in combination with WebRequest or
java.util.Locale, allowing code to register context-specific editors.
The following example demonstrates the use of @InitBinder to configure a
CustomDateEditor for all java.util.Date form properties.
Alternatively, as of Spring 4.2, consider using addCustomFormatter to specify
Formatter implementations instead of PropertyEditor instances. This is
particularly useful if you happen to have a Formatter-based setup in a shared
FormattingConversionService as well, with the same approach to be reused for
controller-specific tweaking of the binding rules.
@Controller
public class MyFormController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
}
// ...
}