赞
踩
SpringBoot工程(其实跟SpringBoot没有关系),在controller中指定了接收参数类型为java.util.Date
,但是前端不管是发来日期字符串还是时间戳,都报错Failed to convert property value of type java.lang.String to required Date
SpringMVC不能自动转换日期字符串或者时间戳为java.util.Date
。
Spring有一个日期转换注解@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
可以在接口中将字符串类型参数yyyy-MM-dd HH:mm:ss
转换为java.util.Date
。举例:
- //这是接口使用的参数类
- public class Test {
-
- @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
- private Date startTime;
-
- @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
- private Date endTime;
-
- public Date getStartTime() {
- return startTime;
- }
-
- public void setStartTime(Date startTime) {
- this.startTime = startTime;
- }
-
- public Date getEndTime() {
- return endTime;
- }
-
- public void setEndTime(Date endTime) {
- this.endTime = endTime;
- }
- }
- // 使用上面参数类的接口
- public class TestController {
- @RequestMapping(value = "/ask",method = RequestMethod.POST)
- public void testMethod(Test test) {
- // do something
- }
- }
在controller中添加一个方法,这个方法为当前接口的所有方法处理Date类型转换。
- // 使用上面参数类的接口
- public class TestController {
- // 增加的方法
- @InitBinder
- protected void init(HttpServletRequest request, ServletRequestDataBinder binder) {
- SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss" );
- dateFormat.setLenient(false); //是否严格解析时间 false则严格解析 true宽松解析
- binder.registerCustomEditor( Date.class, new CustomDateEditor(dateFormat, false));
- }
-
- @RequestMapping(value = "/ask",method = RequestMethod.POST)
- public void testMethod(Test test) {
- // do something
- }
- }
实际上,这里不仅仅可以来处理时间类型,还可以来处理其它的数据类型(非基本类型数据)如CustomDateEditor、CustomBooleanEditor、CustomNumberEditor等。
如果嫌弃在每个controller中添加这个方法不方便管理,还可以使用Spring AOP功能,新建一个类。
- @ControllerAdvice
- public class DateHandler {
-
- @InitBinder
- public void initBinder(WebDataBinder binder) {
- SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- dateFormat.setLenient(false); //是否严格解析时间 false则严格解析 true宽松解析
- binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
- }
- }
这个切面方法会为每一个controller处理日期转换。
参考文章:
作者:猫仙草
链接:https://www.jianshu.com/p/cb108ecbec89
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。