Spring MVC 自定義類型轉換器
阿新 • • 發佈:2018-07-01
import rtm ring type class ota 轉換 spa 新建
新建一個自定義轉換器
import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import com.atguigu.springmvc.crud.entities.Department; import com.atguigu.springmvc.crud.entities.Employee; @Component public class EmployeeConverter implements Converter<String, Employee> { @Overridepublic Employee convert(String source) { if(source != null){ String [] vals = source.split("-"); //[email protected] if(vals != null && vals.length == 4){ String lastName = vals[0]; String email = vals[1]; Integer gender= Integer.parseInt(vals[2]); Department department = new Department(); department.setId(Integer.parseInt(vals[3])); Employee employee = new Employee(null, lastName, email, gender, department); System.out.println(source + "--convert--" + employee); return employee; } } return null; } }
配置xml
<!-- 配置 ConversionService --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <ref bean="employeeConverter"/> <!-- 自定義的類名,首字母小寫 --> </set> </property> </bean>
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
Spring MVC 自定義類型轉換器