【作用】WebDataBinder实现将请求request绑定到复杂属性时的请求字符string到属性的转换
【原因】一般的string, int, long会自动绑定到参数,但是自定义的格式spring就不知道如何绑定了
【实现】所以要继承PropertyEditorSupport,实现自己的属性编辑器PropertyEditor,绑定到WebDataBinder ( binder.registerCustomEditor),覆盖方法setAsText,需要注解@InitBinder
【样例】表单发送数据mydate,格式201801–10,自定义数据绑定
@Controller
public class UserController {
//【控制器内】初始化绑定器
//绑定一个属性编辑器
//参数列表是解析后的类型class,要解析的属性field,自定义的PropertyEditor
//表示当前控制器的所有类型是Date的mydate使用MyDateEditor属性编辑器
//如果没有"mydate",表示所有Date都使用同一个MyDateEditor属性编辑器
@InitBinder
public void bind (WebDataBinder webDataBinder){
webDataBinder.registerCustomEditor(Date.class,"mydate",new MyDateEditor());
}
//user的mydate属性接收【表单】提交的参数,格式201801--10
@RequestMapping("/date")
public void find( User user, HttpServletResponse response) throws Exception{
response.getWriter().write("my date:"+user.getMydate());
}
}
//User.java
public class User {
private Date mydate;
public Date getMydate() {
return mydate;
}
public void setMydate(Date mydate) {
this.mydate = mydate;
}
}
//绑定多个属性编辑器,都是同一类型data,不同的属性名(orderDate,shipDate)
@InitBinder
public void bindingPreparation(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, "orderDate", new MyDateEditor());
binder.registerCustomEditor(Date.class, "shipDate", new MyDateEditor2());
}
//MyDateEditor.java
import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyDateEditor extends PropertyEditorSupport{
@Override
public String getAsText() {
//获取属性值
Date date = (Date) getValue();
DateFormat dateFormat = new SimpleDateFormat("yyyyMM--dd");
String str = dateFormat.format(date);
String mydate = str.substring(0,4)+str.substring(4,6)+"--"+str.substring(8,10);
System.out.println(mydate);
return mydate;
}
//text: 201801--10
@Override
public void setAsText(String text) throws IllegalArgumentException {
DateFormat dateFormat = new SimpleDateFormat("yyyyMM--dd");
try {
System.out.println(dateFormat.parse(text));
//设置属性值
setValue(dateFormat.parse(text));
}catch (ParseException e){
System.out.println("ParseException....................");
}
}
}
【测试】使用postman
1. form-data模式 或x-www-form-urlencoded模式
http://localhost:8080/date/
设置key mydate value 201801–10
2. raw模式
设置headers key Content-Type value application/x-www-form-urlencoded
设置body mydate=201801–10
【结论】spring会根据http头Content-Type:application/x-www-form-urlencoded,判断是表单提交,从而调用自定义属性编辑器