@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));
}
// ...
}
前台的date类型form数据不能传值到controller中的参数中,看到后台提示date类型转换失败。
@initBinder
可以直接在你的controller
中提供数据绑定。initbinder 方法不能有返回值,一般是返回void
。
在需要日期转换的Controller中使用SpringMVC的注解@initbinder
和Spring自带的WebDateBinder
类来操作。
WebDataBinder是用来绑定请求参数到指定的属性编辑器.由于前台传到controller里的值是String类型的,当往Model里Set这个值的时候,如果set的这个属性是个对象,Spring就会去找到对应的editor进行转换,然后再SET进去。