日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.logException Resolved

發布時間:2025/3/12 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.logException Resolved 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

場景:

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類型)是沒有問題的!

    總結

    以上是生活随笔為你收集整理的org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.logException Resolved的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。