Spring注解:InitBinder

注解 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 的對象。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容