org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.logException Resolved
場(chǎng)景:
spring項(xiàng)目中無(wú)法訪問(wèn)到對(duì)應(yīng)controller,查看日志,沒(méi)有報(bào)錯(cuò),只有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]直接來(lái)說(shuō)就是字符串無(wú)法轉(zhuǎn)為Date類(lèi)型。
引起原因是大部分人使用Date格式作為controller接口的參數(shù),導(dǎo)致springmvc無(wú)法將String轉(zhuǎn)為Date,已知springmvc內(nèi)置了一系列的轉(zhuǎn)換,不過(guò)都是基本類(lèi)型到包裝類(lèi)以及String到包裝類(lèi),和List、Set、Map等。但是對(duì)類(lèi)似String轉(zhuǎn)Date還是無(wú)能為力的。
2種解決辦法:
參數(shù)改為String類(lèi)型,在后端處理String到Date的轉(zhuǎn)換,而不是交給SpringMVC來(lái)處理。
寫(xiě)轉(zhuǎn)換類(lèi)實(shí)現(xiàn)org.springframework.core.convert.converter.Converter,并在SpringMVC中注冊(cè)。
該Converter接口較為簡(jiǎn)單,代碼略
<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項(xiàng)目:
@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默認(rèn)已經(jīng)提供了很多自動(dòng)轉(zhuǎn)換,查看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);}已經(jīng)注冊(cè)的子類(lèi):
比如有從StringToBooleanConverter,就說(shuō)明參數(shù)String到Boolean(參數(shù)以Boolean類(lèi)型)是沒(méi)有問(wèn)題的!
總結(jié)
以上是生活随笔為你收集整理的org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.logException Resolved的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: erlang精要(10)-erl(2)
- 下一篇: erlang精要(13)-基本语法(1)