解决org.springframework.web.method.annotation.MethodArgumentTypeMismatchException警告
场景:spring项目中无法访问到对应controller,查看日志,没有报错,只有warnring:org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.logException Resolved [org.springframework.web.method.annotation.Method...
场景:
spring项目中无法访问到对应controller,查看日志,没有报错,只有warnring:
org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.logException Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:
Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type
[@org.springframework.web.bind.annotation.RequestParam java.util.Date] for value '2019-06-21'; nested exception is java.lang.IllegalArgumentException]
直接来说就是字符串无法转为Date类型。
引起原因是大部分人使用Date格式作为controller接口的参数,导致springmvc无法将String转为Date,已知springmvc内置了一系列的转换,不过都是基本类型到包装类以及String到包装类,和List、Set、Map等。但是对类似String转Date还是无能为力的。
2种解决办法:
1. 参数改为String类型,在后端处理String到Date的转换,而不是交给SpringMVC来处理。
2 写转换类实现org.springframework.core.convert.converter.Converter,并在SpringMVC中注册。
该Converter接口较为简单,代码略
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.l.utils.StringToDateConverter"/>
</set>
</property>
</bean>
<mvc:annotation-driven conversion-service="conversionService"/>
如果是springboot项目:
@Bean
public ConversionService conversionService() {
FormattingConversionServiceFactoryBean factory = new FormattingConversionServiceFactoryBean();
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setDateFormatter(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
factory.setFormatterRegistrars(Collections.singleton(registrar));
factory.afterPropertiesSet();
return factory.getObject();
}
原理:
springmvc默认已经提供了很多自动转换,查看org.springframework.context.support.ConversionServiceFactoryBean源码:

查看Converter接口:
@FunctionalInterface
public interface Converter<S, T> {
/**
* Convert the source object of type {@code S} to target type {@code T}.
* @param source the source object to convert, which must be an instance of {@code S} (never {@code null})
* @return the converted object, which must be an instance of {@code T} (potentially {@code null})
* @throws IllegalArgumentException if the source cannot be converted to the desired target type
*/
@Nullable
T convert(S source);
}
已经注册的子类:
比如有从StringToBooleanConverter,就说明参数String到Boolean(参数以Boolean类型)是没有问题的!
「智能机器人开发者大赛」官方平台,致力于为开发者和参赛选手提供赛事技术指导、行业标准解读及团队实战案例解析;聚焦智能机器人开发全栈技术闭环,助力开发者攻克技术瓶颈,促进软硬件集成、场景应用及商业化落地的深度研讨。 加入智能机器人开发者社区iRobot Developer,与全球极客并肩突破技术边界,定义机器人开发的未来范式!
更多推荐



所有评论(0)