SpringMVC自定義資料型別轉換器
阿新 • • 發佈:2021-03-12
要解決的問題
springMVC自帶了很多自動的資料型別轉換器,比如String轉Integer,String轉Date等,但在String轉Date中,2021-01-01無法自動轉為Date,所以就需要我們自定義一個數據型別轉換類;
步驟
1、寫一個String轉Date的轉換類,該類實現Converter介面,並複寫其中的convert方法
package cn.gpxxg.utils.converter; import org.springframework.core.convert.converter.Converter; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * 型別轉換,把String轉為Date */ public class StringToDate implements Converter<String, Date> { @Override public Date convert(String s) { if (s == null) throw new RuntimeException("請您傳入資料"); DateFormat date = new SimpleDateFormat("yyyy-MM-dd"); Date parse = null; try { parse = date.parse(s); } catch (ParseException e) { e.printStackTrace(); } return parse; } }
2、在springmvc配置檔案中配置自定義型別轉換器,注入ConversionServiceFactoryBean並加入我們自定義的轉換類,並在mvc:annotation-driven中開啟自定義型別轉換的支援
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--建立容器時要掃碼的包--> <context:component-scan base-package="cn.gpxxg"></context:component-scan> <!--載入檢視解析器進容器--> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--配置跳轉地址的字首--> <property name="prefix" value="/WEB-INF/pages/"></property> <!--配置跳轉地址的字尾--> <property name="suffix" value=".jsp"></property> </bean> <!--配置自定義型別轉換器--> <bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="cn.gpxxg.utils.converter.StringToDate"></bean> </set> </property> </bean> <!--springMVC框架開啟註解支援--> <mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/> </beans>
3、寫個頁面自測吧