Springmvc提供了数据类型的自定义格式转换功能,从而解决从前端提交的字符串转换在日期、数据的简单方法。
- 在要实再绑定的Controller中添加绑定方法
@InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); sdf.setLenient(false);// 让日期格式严格遵定日期格式 binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true)); binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, true)); }
-
也可以写一个类,在里面实现这个方法,给其它要绑定的controller继承
public class BaseController { @InitBinder public void initBinder(WebDataBinder binder) { System.out.println("bider----------------"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); sdf.setLenient(false);// 让日期格式严格遵定日期格式 binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true)); binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, true)); } } @Controller public class UserController extends BaseController{ ........ }
-
也可以写一个类,用@ControllerAdvice来配置全局的
WebDataBinde
@ControllerAdvice public class BaseController { @InitBinder public void initBinder(WebDataBinder binder) { System.out.println("bider----------------"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); sdf.setLenient(false);// 让日期格式严格遵定日期格式 binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true)); binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, true)); } }
-
更简便的方法在模型类中参应属性上添加@DateTimeFormat(pattern ="yyyy-MM-dd" )注解
public class User { private int id; private String name; private int age; private String pwd; @DateTimeFormat(pattern ="yyyy-MM-dd" ) private Date birthday; private Department dpt; getter...... setter...... } 但如果在mvc中有配置类型转换器,但同时又想对数据进行格式化,需将类更改成FormattingConversionServiceFactoryBean <bean id="conversionServer" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> ........ </set> </property> </bean>
其间要注意数据的类型一定要统一