类型转换:
请求url: http://localhost:8080/SSHDemo2/stu/pro?s=zk,19
传入参数 s=zk,19 转换为Student
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "toString - name="+name+";age="+age;
}
}
public class StudentEditor extends PropertyEditorSupport{
@Override
public void setAsText(String text) throws IllegalArgumentException {
Student s = new Student();
String[] attrs = text.split(",");
if(attrs.length==1){
s.setName(attrs[0]);
}
if(attrs.length==2){
s.setName(attrs[0]);
s.setAge(Integer.parseInt(attrs[1]));
}
System.out.println("setAsText");
setValue(s);
}
@Override
public String getAsText() {
System.out.println("getAsText");
return getValue().toString();
}
}
@Controller
@RequestMapping("/stu")
public class StudentController {
@RequestMapping("/pro")
public String stuPropertyEditor(@RequestParam("s") Student s){
System.out.println("name="+s.getName()+";age="+s.getAge());
return "success";
}
@InitBinder
public void initBinder(WebDataBinder binder){
System.out.println("init..");
binder.registerCustomEditor(Student.class, new StudentEditor());
}
}
此时也可以不要@InitBinder,因为bean为Student则StudentEditor会默认为它的属性编辑器