> 用于controller的方法上,配置這個controller的屬性綁定規則
# **1.對數據綁定進行設置**
WebDataBinder中有很多方法可以對數據綁定進行具體的設置:比如我們設置name屬性為非綁定屬性(也可以設置綁定值setAllowedFields):
在Controller中添加一個方法:
```
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.setDisallowedFields("name");
}
```
這樣表單中的name屬性就不會綁定到方法參數上
# **2.注冊已有的編輯器**
1. WebDataBinder是用來綁定**請求參數到指定的屬性編輯器**.
2. 由于前臺傳到controller里的值是String類型的,當往Model里Set這個值的時候,如果set的這個屬性是個對象,Spring就會去找到對應的editor進行轉換,然后再set進去!
3. Spring自己提供了大量的實現類(如下圖所示的在org.springframwork.beans.propertyEditors下的所有editor),諸如CustomDateEditor ,CustomBooleanEditor,CustomNumberEditor等許多,基本上夠用。 ?在平時使用SpringMVC時,會碰到javabean中有Date類型參數,表單中傳來代表日期的字符串轉化為日期類型,SpringMVC默認不支持這種類型的轉換。我們就需要手動設置時間格式并在webDateBinder上注冊這個編輯器!
如下,這個時間Editer,對時間屬性進行綁定的時候,按照如下格式進行轉換
~~~
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
~~~
# **3.注冊自定義編輯器**
使用自定義編輯器就是在第二個的基礎上添加個自定義編輯器就行了,自定義的編輯器類需要繼承
~~~
org.springframework.beans.propertyeditors.PropertiesEditor;
~~~
并重寫其setAsText和getAsText兩個方法就行了!
```
public class DoubleEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (text == null || text.equals("")) {
text = "0";
}
setValue(Double.parseDouble(text));
}
@Override
public String getAsText() {
return getValue().toString();
}
}
```
然后在InitBinder方法中注冊就行。
# **3.設置屬性的前綴可以實現參數綁定**
入代碼所示:
jsp:
```
<form action="/testBean" method="post">
name: <input type="text" name="u.name"> <br>
age: <input type="text" name="u.age"> <br>
name: <input type="text" name="s.name"> <br>
age: <input type="text" name="s.age"> <br>
<input type="submit">
</form>
```
controller:
```
@InitBinder("user")
public void init1(WebDataBinder binder) {
binder.setFieldDefaultPrefix("u.");
}
@InitBinder("stu")
public void init2(WebDataBinder binder) {
binder.setFieldDefaultPrefix("s.");
}
@RequestMapping("/testBean")
public ModelAndView testBean(User user, @ModelAttribute("stu") Student stu) {
System.out.println(stu);
System.out.println(user);
String viewName = "success";
ModelAndView modelAndView = new ModelAndView(viewName);
modelAndView.addObject("user", user);
modelAndView.addObject("student", stu);
return modelAndView;
}
```
> `@InitBinder("user")`括號內的參數為類的首字母小寫(默認命名規則),也可以用`@ModelAttribute("stu")`做限定.