问题
今天开发时,发现页面表单中的Date类型,从js层向controller层传参的时候异常,始终传参失败。后来发现在使用SpingMVC框架时,经常会遇到页面某些数据类型是Date、Integer、Double等的数据要绑定到控制器的实体,或者控制器需要接受这些数据,如果这类数据类型不做处理的话将无法绑定。
解决方法
在controller层新增一段代码,即可解决问题:
// An highlighted block
@InitBinder
public void initBinder(WebDataBinder binder) {
//"yyyy-MM-dd hh:mm:ss",页面传参的时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
}