客户端在向服务器发送数据时,发送的是字符串,这些字符串可以自动的绑定到基本数据类型上去。但是对于复杂的数据类型,就需要进行类型转换。比如字符串类型转换为时间类型。一下将介绍两种类型转换的方法:
第一种方法是通过框架提供的,写一个类,实现Converter
public class StuConvert implements Converter<String,Student> {
@Override public Student convert(String s) {
String[] allInfo=s.split(":");
Student student=new Student();
student.setName(allInfo[0]);
student.setAge(Integer.parseInt(allInfo[1]));
student.setSex(allInfo[2]);
return student;
}
}
在mvc的配置中将这个转换器添加到默认转换器中:
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean"><!--默认的类型转化服务-->
<property name="converters">
<list>
<bean class="com.convert.StuConvert" /><!--将自定义的类型转换器加入-->
</list>
</property>
</bean>
controller:
@RequestMapping(value = "hello8.htm",method = RequestMethod.GET)
public void handler8(@RequestParam("stu") Student student)
{
System.out.println(student);
}
构建一个超链接,用get传参,参数的内容为对象的属性值:
<a href="firstMVC/hello8.htm?stu=zhangsan:25:M">Hello8</a>
输出到控制台的信息:
Student{name='zhangsan', age=25, sex='M'}
第二种方法是利用java提供的方法:
写一个转换器类,继承PropertyEditorSupport类,重写setAsText方法:
public class StuConvertByjava extends PropertyEditorSupport {
@Override public void setAsText(String text) throws IllegalArgumentException {
Student student=new Student();
String[] stuInof=text.split(":");
student.setName(stuInof[0]);
student.setAge(Integer.parseInt(stuInof[1]));
student.setSex(stuInof[2]);
setValue(student);
}
}
告诉spring这个转换器:在controller类中加上第一个方法即可,在配置文件中不用配置。其他地方都一样。
@InitBinder
public void initBinder(WebDataBinder binder)
{
binder.registerCustomEditor(Student.class,new StuConvertByjava());
}
@RequestMapping(value = "hello8.htm",method = RequestMethod.GET)
public void handler8(@RequestParam("stu") Student student)
{
System.out.println(student);
}
上一篇 |
---The End---
| 下一篇 |