1、创建 StudentConverter 类,并实现 org.springframework.core.convert.converter.Converter 接口,这样它就成为 了一个自定义数据类型转换器,需要指定泛型<String, Student>,表示将 String 类型转为 Student 类型。
(1)Student 实体类
import lombok.Data;
@Data
public class Student {
private Integer id;
private String name;
private Integer age;
}
(2)StudentConverter 类
import com.southwind.pojo.Student;
import org.springframework.core.convert.converter.Converter;
public class StudentConverter implements Converter<String, Student> {
@Override
public Student convert(String source) {
String[] args = source.split("-");
Student student = new Student();
student.setId(Integer.parseInt(args[0]));
student.setName(args[1]);
student.setAge(Integer.parseInt(args[2]));
return student;
}
}
(3)Controller
import com.southwind.pojo.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
@Controller
@RequestMapping("/converter")
public class ConverterController {
@RequestMapping("/student")
@ResponseBody
public Student student(Student student, HttpServletResponse response){
response.setCharacterEncoding("UTF-8");
return student;
}
}
(4)springmvc.xml
<?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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置自动扫描-->
<context:component-scan base-package="com.southwind"></context:component-scan>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.southwind.converter.StudentConverter"></bean>
</list>
</property>
</bean>
<mvc:annotation-driven conversion-service="conversionService">
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/html;charset=UTF-8"></property>
</bean>
<!--fastjson-->
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"></bean>
</mvc:message-converters>
</mvc:annotation-driven>
</beans>
在 springmvc.xml 中配置 conversionService bean,这个 bean 是 rg.springframework.context.support.ConversionServiceFactoryBean 的实例化对象,同时 bean 中必须包含一个 converters 属性,在其中注册所有需要使用的自定义转换器。