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>
其间要注意数据的类型一定要统一
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/71220.html