SpringBoot提交日期参数失败的解决方法 ConversionFailedException

如果你有类似如下报错信息,可阅读此文尝试解决:

2018-08-18 14:05:17.687  WARN 17100 --- [p-nio-80-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 4 errors
Field error in object 'sysUserDO' on field 'userBecomeTime': rejected value []; codes [typeMismatch.sysUserDO.userBecomeTime,typeMismatch.userBecomeTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [sysUserDO.userBecomeTime,userBecomeTime]; arguments []; default message [userBecomeTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'userBecomeTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value ''; nested exception is java.lang.IllegalArgumentException]
Field error in object 'sysUserDO' on field 'userBirthday': rejected value []; codes [typeMismatch.sysUserDO.userBirthday,typeMismatch.userBirthday,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [sysUserDO.userBirthday,userBirthday]; arguments []; default message [userBirthday]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'userBirthday'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value ''; nested exception is java.lang.IllegalArgumentException]
Field error in object 'sysUserDO' on field 'userDimissionTime': rejected value []; codes [typeMismatch.sysUserDO.userDimissionTime,typeMismatch.userDimissionTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [sysUserDO.userDimissionTime,userDimissionTime]; arguments []; default message [userDimissionTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'userDimissionTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value ''; nested exception is java.lang.IllegalArgumentException]
Field error in object 'sysUserDO' on field 'userJoinTime': rejected value []; codes [typeMismatch.sysUserDO.userJoinTime,typeMismatch.userJoinTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [sysUserDO.userJoinTime,userJoinTime]; arguments []; default message [userJoinTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'userJoinTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value ''; nested exception is java.lang.IllegalArgumentException]

前台像后台传递参数带日期是,springboot自动绑定会失败

比如:

前台代码:

后台接收代码:

报错信息:

 

 

下面给出解决方法:

1.创建一个class 名称:StringToDateConverter  稍后会用到此类

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToDateConverter implements Converter<String, Date> {
	private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
	private static final String shortDateFormat = "yyyy-MM-dd";
	private static final String dateFormat2 = "yyyy/MM/dd HH:mm:ss";
	private static final String shortDateFormat2 = "yyyy/MM/dd";

	@Override
	public Date convert(String source) {
		if (StringUtils.isBlank(source)) {
			return null;
		}
		source = source.trim();
		try {
			SimpleDateFormat formatter;
			if (source.contains("-")) {
				if (source.contains(":")) {
					formatter = new SimpleDateFormat(dateFormat);
				} else {
					formatter = new SimpleDateFormat(shortDateFormat);
				}
				Date dtDate = formatter.parse(source);
				return dtDate;
			} else if (source.contains("/")) {
				if (source.contains(":")) {
					formatter = new SimpleDateFormat(dateFormat2);
				} else {
					formatter = new SimpleDateFormat(shortDateFormat2);
				}
				Date dtDate = formatter.parse(source);
				return dtDate;
			}
		} catch (Exception e) {
			throw new RuntimeException(String.format("parser %s to Date fail", source));
		}

		throw new RuntimeException(String.format("parser %s to Date fail", source));

	}
}

其中StringUtils为apache lang3包,可以自己手写替代,或导包

<!--apache lang3-->
<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-lang3</artifactId>
   <version>3.1</version>
</dependency>

2.添加配置类,把我们写的处理日期的类交给spring,让它知道怎么处理


import com.here.hulk.utils.StringToDateConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.PostConstruct;

@Configuration
public class WebAppConfig {
	@Autowired
	private RequestMappingHandlerAdapter handlerAdapter;


	/**
	 * 此方法解决前台提交的日期参数绑定不正确问题,将自己实现的StringToDateConverter交给spring,让其知道如何进行处理
	 */
	@PostConstruct //@PostContruct是spring框架的注解,在方法上加该注解会在项目启动的时候执行该方法,也可以理解为在spring容器初始化的时候执行该方法。
	public void initEditableValidation() {
		ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter.getWebBindingInitializer();
		if (initializer.getConversionService() != null) {
			GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService();
			genericConversionService.addConverter(new StringToDateConverter());
		}
	}
}

3.重启测试,有问题继续想办法,总是能解决的

 

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值