SpringMVC實現(xiàn)自定義類型轉(zhuǎn)換器
我們在使用SpringMVC時,常常需要把表單中的參數(shù)映射到我們對象的屬性中,我們可以在默認的spring-servlet.xml加上如下的配置即可做到普通數(shù)據(jù)類型的轉(zhuǎn)換,如將String轉(zhuǎn)換成Integer和Double等:
<mvc:annotation-driven />
或
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />
其實 <mvc:annotation-driven /> 標簽會默認創(chuàng)建并注冊一個 RequestMappingHandlerMapping(在Spring3.2之前是DefaultAnnotationHandlerMapping) 和 RequestMappingHandlerAdapter (Spring3.2之前是AnnotationMethodHandlerAdapter),當(dāng)然,如果上下文有對應(yīng)的顯示實現(xiàn)類,將該注解注冊的覆蓋掉。該注解還會創(chuàng)建一個ConversionService,即 FormattingConversionServiceFactoryBean。
如果想把一個字符串轉(zhuǎn)換成其它實體類型,spring沒有提供這樣默認的功能,我們需要自定義類型轉(zhuǎn)換器。
這里有個實體類Employee。
package com.proc; public class Employee { private String name; private Integer age; private String gender; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @Override public String toString() { return "Employee [name=" + name + ", age=" + age + ", gender=" + gender + "]"; } }
規(guī)定將字符串轉(zhuǎn)換成實體類的規(guī)則為: name-age-gender
那么接下來就寫一個類型轉(zhuǎn)換器,需要實現(xiàn)一個接口org.springframework.core.convert.converter.Converter
package com.proc; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; @Component public class EmployeeConverter implements Converter<String, Employee> { @Override public Employee convert(String str) { Employee emp=null; //字符串格式 name-age-gender if(str!=null && str.split("-").length==3){ emp=new Employee(); String[] arr=str.split("-"); emp.setName(arr[0]); emp.setAge(Integer.parseInt(arr[1])); emp.setGender(arr[2]); } return emp; } }
這里我們?yōu)檗D(zhuǎn)換器加上@Component注解,是為了讓Spring自動掃描該轉(zhuǎn)換器到容器中。這樣就不用通過配置文件配置<bean>了
接下來編寫控制器
package com.proc; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class EmployeeController { @RequestMapping("/add") public String add(@RequestParam("employee") Employee employee){ System.out.println(employee); return "add"; } }
這里可以看到,參數(shù)的名字為employee,所有要為請求定義一個employee參數(shù),該參數(shù)傳入需要轉(zhuǎn)換的字符串
除此之外,我們還需要在spring配置文件中配置,如下類容。讓轉(zhuǎn)換器生效
<?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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <context:component-scan base-package="com.proc"></context:component-scan> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/"/> <property name="suffix" value=".jsp"></property> </bean> <mvc:annotation-driven conversion-service="conversionService"/> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <ref bean="employeeConverter"/> </set> </property> </bean> </beans>
測試代碼:http://localhost:8080/springmvc-1/add?employee=caoyc-18-male
結(jié)果輸出:Employee [name=caoyc, age=18, gender=male]
上面配置文件中我們使用配置了一個ConversionServiceFactoryBean。雖然可以這樣,但不建議。我們通常用org.springframework.format.support.FormattingConversionServiceFactoryBean
為什么要這樣用呢?這樣用的好處是什么呢?
使用FormattingConversionServiceFactoryBean可以讓SpringMVC支持@NumberFormat和@DateTimeFormat等Spring內(nèi)部自定義的轉(zhuǎn)換器。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
完整java開發(fā)中JDBC連接數(shù)據(jù)庫代碼和步驟
這篇文章主要介紹了完整java開發(fā)中JDBC連接數(shù)據(jù)庫代碼和步驟,需要的朋友可以參考下2015-09-09Java異常處理操作 Throwable、Exception、Error
這篇文章主要介紹了Java異常處理操作 Throwable、Exception、Error,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06Jenkins如何使用DockerFile自動部署Java項目
這篇文章主要介紹了Jenkins如何使用DockerFile自動部署Java項目,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08springBoot?@Scheduled實現(xiàn)多個任務(wù)同時開始執(zhí)行
這篇文章主要介紹了springBoot?@Scheduled實現(xiàn)多個任務(wù)同時開始執(zhí)行,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12