场景:
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种解决办法:
-
参数改为String类型,在后端处理String到Date的转换,而不是交给SpringMVC来处理。
-
写转换类实现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项目:
@Beanpublic 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*/@NullableT convert(S source);}
已经注册的子类:
比如有从StringToBooleanConverter,就说明参数String到Boolean(参数以Boolean类型)是没有问题的!