场景:
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还是无能为力的。
该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类型)是没有问题的!
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/qq_43842093/article/details/121582159
内容来源于网络,如有侵权,请联系作者删除!