您的位置:首页 > 其它

关于表单提交时date类型的转换问题

2018-02-01 11:41 274 查看
在做向数据库添加数据的功能时,遇到了这个问题,百度了一下发现可以这样解决,再此记录一下。

前台<input name="birthday"/>,
后台Controller中的一个方法public String login(User user){...}.
前台birthday对应user.birthday,当然user的这个属性是Date类型,前台传过来的是字符类型,
一般情况下spring就会自动进行前后台的自动匹配,但是数据类型不一致会报错,说前台传过来的数据不合法.
只需在Controller中定义一个方法:
@InitBinder
public void initBinder(ServletRequestDataBinder binder){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
作用即是将前台传入的String类型birthday经SimpleDateFormat转换成Date类型birthday从而和user.birthday匹配.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐