类型转换器
a.Spring自带一些 常见的类型转换器:
public String testDelete(@PathVariable(“id”) String id) ,即可以接受int类型数据id 也可以接受String类型的id
b.可以自定义类型转换器
i.编写 自定义类型转器的类 (实现Converter接口)
//泛型
public class MyConverter implements Converter<String,Student>{
@Override
public Student convert(String source) {// 前端:2-zs-23
//source接受前端传来的String:2-zs-23
String[] studentStrArr = source.split("-") ;
Student student = new Student();
student.setId( Integer.parseInt( studentStrArr[0]) );
student.setName(studentStrArr[1]);
student.setAge(Integer.parseInt(studentStrArr[2] ));
return student;
}
}
ii.配置:将MyConverter加入到springmvc中
<!-- 1将 自定义转换器 纳入SpringIOC容器 -->
<bean id="myConverter" class="org.lanqiao.converter.MyConverter"></bean>
<!-- 2将myConverter再纳入 SpringMVC提供的转换器Bean -->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<ref bean="myConverter"/>
</set>
</property>
</bean>
<!-- 3将conversionService注册到annotation-driven中 -->
<!--此配置是SpringMVC的基础配置,很功能都需要通过该注解来协调 -->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
用
index.jsp
<form action="handler/testConverter" method="post">
学生信息:<input name="studentInfo" type="text" /><!-- 2-zs-23 -->
<input type="submit" value="转换">
</form>
handler
@RequestMapping(value="testConverter")
//@RequestParam("studentInfo")是触发转换器的桥梁,将前端数据传给student
public String testConverter(@RequestParam("studentInfo") Student student) {
System.out.println(student.getId()+","+student.getName()+","+student.getAge());
return "success";
}