注解 InitBinder 是用來初始化綁定器Binder的,而Binder是用來綁定數(shù)據(jù)的,換句話說就是將請求參數(shù)轉(zhuǎn)成數(shù)據(jù)對象。
@InitBinder用于在@Controller中標(biāo)注于方法,表示為當(dāng)前控制器注冊一個(gè)屬性編輯器或者其他,只對當(dāng)前的Controller有效。
@InitBinder 有2個(gè)基本用途,類型轉(zhuǎn)換和參數(shù)綁定。
類型轉(zhuǎn)換
比如,將“2019-12-06 16:59:59”這樣的字符串轉(zhuǎn)成 java.util.Date 對象
@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));
}
參數(shù)綁定
比如,html表單是下面這樣的
<form action="/buy" method="post">
name: <input type="text" name="customer.name"> <br>
age: <input type="text" name="customer.customerId"> <br>
name: <input type="text" name="goods.title"> <br>
age: <input type="text" name="goods.price"> <br>
<input type="submit">
</form>
在后臺將以customer為前綴的參數(shù)綁定到Customer對象上,將以goods為前綴的參數(shù)綁定到Goods對象上
@InitBinder("customer")
public void initCustomer(WebDataBinder binder) {
binder.setFieldDefaultPrefix("customer.");
}
@InitBinder("goods")
public void initGoods(WebDataBinder binder) {
binder.setFieldDefaultPrefix("goods.");
}
@PostMapping("/buy")
public ModelAndView buy(Customer customer, @ModelAttribute("goods") Goods goods, ModelAndView mv) {
// do something
return mv;
}
@ModelAttribute("goods") 中的 “goods” 用來指定 @InitBinder("goods")
換句話講
在 initGoods 方法中,將以 goods 為前綴的參數(shù)封裝為名為 goods 的對象;
在 buy 方法中使用 @ModelAttribute("goods") 來接收名為 goods 的對象。