【java基础】WebDataBinder

作用:把字符串形式的参数转换成服务端真正需要的类型的转换工具

那就需要借助于PropertyEditor 来帮助你完成复杂对象的对应关系,这个借口提供了两个方法,将一个property 转成string getAsText(), 另外一个方法是将string类型的值转成property对应的类型。使用起来也很简单,例子如下:

@InitBinder  
public void bindingPreparation(WebDataBinder binder) {  
  DateFormat dateFormat1 = new SimpleDateFormat("d-MM-yyyy");  
  CustomDateEditor orderDateEditor = new CustomDateEditor(dateFormat1, true);  
  DateFormat dateFormat2 = new SimpleDateFormat("MMM d, YYYY");  
  CustomDateEditor shipDateEditor = new CustomDateEditor(dateFormat2, true);  
  binder.registerCustomEditor(Date.class, "orderDate", orderDateEditor);  
  binder.registerCustomEditor(Date.class, "shipDate", shipDateEditor);  
}  
方便的完成request和property之间的binder
WebDataBinder是用来绑定请求参数到指定的属性编辑器,由于其那台传到controller里面的值是String类型的,当往model里面set这个值的时候,如果set的这个属性是个对象,Spring就会找到对应的EDITOR进行转换,然后再set进去。

猜你喜欢

转载自blog.csdn.net/zlt995768025/article/details/80471623