在做向数据库添加数据的功能时,遇到了这个问题,百度了一下发现可以这样解决,再此记录一下。
前台<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匹配.
本文介绍如何解决Spring框架中前台传递的字符串类型数据与后台期望的日期类型不匹配的问题。通过在Controller中使用@InitBinder注解定义一个自定义编辑器,将字符串类型的日期转换为Date类型。
1228

被折叠的 条评论
为什么被折叠?



