一.简单转换-Spring自带的转换Editor
以接收Date类型为例:
@RequestMapping("/testFunc")
public String testFunc(String name,Date now){
System.out.println(name);
System.out.println(now);
return "welcome";
}
@InitBinder //参数绑定注解
public void convert(WebDataBinder dataBinder){ //这里以Date类型为例,convert是自定义方法,此方法可封装于父类控制器中
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//自定义格式
dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, false));
}
二.复杂转换-自定义转换,自己编写Editor
(这里实现将接收到的参数拼接+"转换了"的功能,以String类型为例)
1.自定义Editor类
public class MyEditor extends PropertyEditorSupport { //继承PropertyEditorSupport
@Override
public String getAsText() {
return getValue().toString();
}
@Override
public void setAsText(String text) throws IllegalArgumentException {//String类型
setValue(text+"转换了");
}
}
2.注册
@InitBinder
public void convert(WebDataBinder dataBinder){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, false));
dataBinder.registerCustomEditor(String.class, new MyEditor());
}