目錄
一. 作用
二. 前期准备
三. Get请求 + URL传值处理
4.1 前台-test16.html
5.5 Controller层
5.6 效果
四. Post请求 + 表单传值 + 自定义日期属性绑定器
5.3 form实体类
五. 其他自定义属性编辑器实例
5.1 自定义SexPropertyEditor
5.2 自定义StringToListPropertyEditor
5.4 前端
六. 多个@InitBinder注解修饰的方法
七. 其他用法
首頁 Java java教程 SpringBoot @InitBinder註解綁定請求參數的方法是什麼

SpringBoot @InitBinder註解綁定請求參數的方法是什麼

May 11, 2023 pm 01:31 PM
springboot @initbinder

    一. 作用

    作用于Controller层中,在Controller层的方法执行前执行,主要作用是初始化当前Controller层的数据绑定器(或者属性绑定器),帮助完成数据处理和数据绑定。

    被该注解修饰的方法会有一个形参WebDataBinder,可以帮我们将request请求中的参数处理绑定到JavaBean中。

    SpringBoot @InitBinder註解綁定請求參數的方法是什麼

    二. 前期准备

    import lombok.Data;
    
    import java.math.BigDecimal;
    import java.util.Date;
    
    @Data
    public class Test16Form {
    
        private String name;
    
        private String sex;
    
        private Date birthday;
    
        private BigDecimal money;
    }
    登入後複製

    三. Get请求 + URL传值处理

    3.1 前台-test16.html

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <div>
        <button id="getBtn">发送get请求</button><br>
    </div>
    </body>
    <script type="text/javascript" th:src="@{/js/public/jquery-3.6.0.min.js}"></script>
    <script>
        $("#getBtn").click(function() {
            
            const urlSearchParams = new URLSearchParams();
            // ????含有空格
            urlSearchParams.append("name", "贾飞天   ");
            urlSearchParams.append("sex", "男");
            // ????值为yyyy-MM-dd HH:mm:ss格式的日期字符串
            urlSearchParams.append("birthday", "2022-11-11 12:12:12");
            urlSearchParams.append("money", "10000");
    
            const url = `/test16/receiveGet?${urlSearchParams.toString()}`;
            $.ajax({
                url,
                type: &#39;GET&#39;,
                success: function (data, status, xhr) {
                    console.log(data);
                }
            });
        });
    </script>
    </html>
    登入後複製

    3.2 Controller层

    StringTrimmerEditorCustomDateEditor是框架自带的属性处理器

    import org.springframework.beans.propertyeditors.CustomDateEditor;
    import org.springframework.beans.propertyeditors.StringTrimmerEditor;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.WebDataBinder;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.servlet.ModelAndView;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    @Controller
    @RequestMapping("/test16")
    public class Test16Controller {
    
        @InitBinder
        public void formBinder(WebDataBinder binder) {
    
            // 只要是String类型,就去除字符串前后的空格
            binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    
            // 只有当属性名为birthday且为Date类型的才使用使用框架自带的CustomDateEditor编辑器将String处理为Date
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            binder.registerCustomEditor(Date.class, "birthday", new CustomDateEditor(df, true));
        }
    
        @GetMapping("/init")
        public ModelAndView init() {
    
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("test16");
            return modelAndView;
        }
    
        @GetMapping("/receiveGet")
        @ResponseBody
        public void receiveGet(Test16Form form) {
    
            System.out.println(form);
        }
    }
    登入後複製

    3.3 效果

    • 字符串两端的空格被去除

    • String格式的日期被转换为Date格式的日期

    SpringBoot @InitBinder註解綁定請求參數的方法是什麼

    四. Post请求 + 表单传值 + 自定义日期属性绑定器

    4.1 前台-test16.html

    表单提交的数据若包含List<实体类>这种数据结构
    在前台需要用 form对应的属性名[下标].实体类属性名 这种方式准备数据

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <div>
        <button id="postBtn">发送post请求</button><br>
    </div>
    </body>
    <script type="text/javascript" th:src="@{/js/public/jquery-3.6.0.min.js}"></script>
    <script>
        $("#postBtn").click(function() {
    
            const paramObj = {
                name: "贾飞天    ",
                sex: &#39;不明&#39;,
                money: "10000",
                // yyyy-MM-dd HH:mm:ss格式
                birthday: &#39;2022-11-11 12:12:12&#39;,
                // 后台中的List实体类区域
                "tableList[0].id": 1,
                "tableList[0].address": &#39;测试address    &#39;,
                "tableList[0].hobby": &#39;测试hobby     &#39;,
                // yyyy年MM月dd日 HH:mm:ss格式
                "tableList[0].workDate": &#39;2022年11月11日 14:14:14&#39;,
            };
    
            $.ajax({
                url: `/test16/receivePost`,
                type: &#39;POST&#39;,
                data: paramObj,
                // 表单格式提交
                contentType : &#39;application/x-www-form-urlencoded;charset=utf-8&#39;,
                // 后端返回给前端的数据类型
                dataType: &#39;json&#39;,
                success: function (data, status, xhr) {
                    console.log(data);
                }
            });
        });
    </script>
    </html>
    登入後複製

    4.2 form实体类

    import lombok.Data;
    
    import java.math.BigDecimal;
    import java.util.Date;
    import java.util.List;
    
    @Data
    public class Test16Form {
    
        private String name;
    
        private String sex;
    	
    	// 待转换类型
        private Date birthday;
    
        private BigDecimal money;
    
        private List<Test4Entity> tableList;
    }
    登入後複製
    import lombok.Data;
    import java.util.Date;
    
    @Data
    public class Test4Entity {
    
        private String id;
    
        private String address;
    
        private String hobby;
    	
    	// 待转换类型
        private Date workDate;
    }
    登入後複製

    4.3 Controller层

    我们可以通过PropertyEditorSupport类来实现我们自己的属性编辑器

    import org.springframework.beans.propertyeditors.StringTrimmerEditor;
    import org.springframework.stereotype.Controller;
    import org.springframework.util.ObjectUtils;
    import org.springframework.web.bind.WebDataBinder;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.servlet.ModelAndView;
    import java.beans.PropertyEditorSupport;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    @Controller
    @RequestMapping("/test16")
    public class Test16Controller {
    
        @InitBinder
        public void formBinder(WebDataBinder binder) {
    
            // 只要是String类型,就去除字符串前后的空格
            binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    
            // 自定义日期转换属性处理器
            binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
    
                @Override
                public void setAsText(String dateStr) {
                    DateFormat dateFormat = null;
                    try {
                        if (ObjectUtils.isEmpty(dateStr)) {
                            setValue(dateStr);
                            return;
                        }
    
                        // yyyy-MM-dd HH:mm:ss格式
                        if (dateStr.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
                            dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        }
                        // yyyy年MM月dd日 HH:mm:ss格式
                        else if (dateStr.matches("^\\d{4}年\\d{1,2}月\\d{1,2}日 {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
                            dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                        }
    
                        if (ObjectUtils.isEmpty(dateFormat)) {
                            setValue(null);
                            return;
                        }
    
                        Date parse = dateFormat.parse(dateStr);
                        setValue(parse);
    
                    } catch (Exception ex) {
                        setValue(null);
                    }
                }
            });
        }
    
        @GetMapping("/init")
        public ModelAndView init() {
    
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("test16");
            return modelAndView;
        }
    
        @PostMapping("/receivePost")
        @ResponseBody
        public void receivePost(Test16Form form) {
            System.out.println(form);
        }
    }
    登入後複製

    4.4 效果

    • 可以看到 yyyy-MM-dd HH:mm:ss 和 yyyy年MM月dd日 HH:mm:ss 格式的字符串日期都被转换为Date数类型

    • 因为没有指定转换特定的属性名所对应的数据,所以包括一览中的数据也被成功转换

    • 一览中的字符换的前后空白也被清除,一览中的日期格式的也被成功转换

    SpringBoot @InitBinder註解綁定請求參數的方法是什麼

    五. 其他自定义属性编辑器实例

    5.1 自定义SexPropertyEditor

    对性别进行编辑,如果性别为空或者不为男性或者女性,默认设置为男性

    import org.springframework.util.ObjectUtils;
    
    import java.beans.PropertyEditorSupport;
    import java.util.Arrays;
    import java.util.List;
    
    public class SexPropertyEditor extends PropertyEditorSupport {
    
        private final static List<String> sexList = Arrays.asList("男", "女");
    
        @Override
        public void setAsText(String sex) {
    
            // 当性别为空或者不是男或女的时候,默认设置为男性
            if(ObjectUtils.isEmpty(sex) || !sexList.contains(sex)) {
                setValue("男");
                return;
            }
    
            setValue(sex);
        }
    }
    登入後複製

    5.2 自定义StringToListPropertyEditor

    将参数中的属性名=XXX-XXX-XXX的数据转换为数组

    import org.springframework.util.ObjectUtils;
    
    import java.beans.PropertyEditorSupport;
    
    public class StringToListPropertyEditor extends PropertyEditorSupport {
    
        @Override
        public void setAsText(String text){
    
            if (ObjectUtils.isEmpty(text) || !text.contains("-")) {
                setValue(text);
                return;
            }
            setValue(text.split("-"));
        }
    }
    登入後複製

    5.3 form实体类

    Test16Form01.java

    import lombok.Data;
    
    @Data
    public class Test16Form01 {
    
        private String sex;
    
        private String[] numList;
    
        private String[] addList;
    }
    登入後複製

    5.4 前端

    const url = `/test16/receiveNumListAndSex?sex=不明&numList=1-2-3&addList=4-5-6`;
    $.ajax({
        url,
        type: &#39;GET&#39;,
        success: function (data, status, xhr) {
            console.log(data);
        }
    });
    登入後複製

    5.5 Controller层

    @Controller
    @RequestMapping("/test16")
    public class Test16Controller {
    
        @InitBinder
        public void formBinder(WebDataBinder binder) {
    
            // 当数据类型为String[],且 属性名为 numList 的时候才会起作用
            // 虽然addList也是String[]格式的数据,但是我们并没有指定转换此属性
            binder.registerCustomEditor(String[].class, "numList", new StringToListPropertyEditor());
            
            // 当数据类型为String 且 属性名为 sex 的时候才会起作用
            binder.registerCustomEditor(String.class, "sex", new SexPropertyEditor());
        }
        
        @GetMapping("/receiveNumListAndSex")
        @ResponseBody
        public void receiveNumList(Test16Form01 form) {
            System.out.println(form);
        }
    }
    登入後複製

    5.6 效果

    SpringBoot @InitBinder註解綁定請求參數的方法是什麼

    六. 多个@InitBinder注解修饰的方法

    • 如果@InitBinder注解没有添加value值,则每个请求都会走被其修饰的方法

    • 如果@InitBinder注解有value值,则只有参数的名称与其相同才会走此方法

    import com.example.jmw.common.bindEditor.SexPropertyEditor;
    import com.example.jmw.common.bindEditor.StringToListPropertyEditor;
    import org.springframework.beans.propertyeditors.StringTrimmerEditor;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.WebDataBinder;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.servlet.ModelAndView;
    
    @Controller
    @RequestMapping("/test16")
    public class Test16Controller {
    
        // 注解没有添加value值,每个请求都会走此方法
        @InitBinder
        public void init(WebDataBinder binder) {
            binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
        }
    
        // 指定只有参数名称为test16Form01的,才会走此方法
        @InitBinder("test16Form01")
        public void formBinder(WebDataBinder binder) {
            // 当数据类型为String 且 属性名为 sex 的时候才会起作用
            binder.registerCustomEditor(String.class, "sex", new SexPropertyEditor());
        }
    
        // 指定只有参数名称为test16Form的,才会走此方法
        @InitBinder("test16Form")
        public void receiveGetBinder(WebDataBinder binder) {
            // 当数据类型为String[],且 属性名为 numList 的时候才会起作用
            binder.registerCustomEditor(String[].class, "numList", new StringToListPropertyEditor());
        }
    
        @GetMapping("/receiveGet")
        @ResponseBody
        public void receiveGet(Test16Form form) {
    
            System.out.println(form);
        }
    
        @GetMapping("/receiveNumListAndSex")
        @ResponseBody
        public void receiveNumList(Test16Form01 form) {
            System.out.println(form);
        }
    }
    登入後複製

    SpringBoot @InitBinder註解綁定請求參數的方法是什麼

    七. 其他用法

    • 当前Controller继承父类,在父类中使用@InitBinder注解来修饰的方法

    • 配合@ControllerAdvice注解作用于全局

    以上是SpringBoot @InitBinder註解綁定請求參數的方法是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    本網站聲明
    本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

    熱AI工具

    Undresser.AI Undress

    Undresser.AI Undress

    人工智慧驅動的應用程序,用於創建逼真的裸體照片

    AI Clothes Remover

    AI Clothes Remover

    用於從照片中去除衣服的線上人工智慧工具。

    Undress AI Tool

    Undress AI Tool

    免費脫衣圖片

    Clothoff.io

    Clothoff.io

    AI脫衣器

    AI Hentai Generator

    AI Hentai Generator

    免費產生 AI 無盡。

    熱門文章

    R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
    3 週前 By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O.最佳圖形設置
    3 週前 By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O.如果您聽不到任何人,如何修復音頻
    3 週前 By 尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25:如何解鎖Myrise中的所有內容
    3 週前 By 尊渡假赌尊渡假赌尊渡假赌

    熱工具

    記事本++7.3.1

    記事本++7.3.1

    好用且免費的程式碼編輯器

    SublimeText3漢化版

    SublimeText3漢化版

    中文版,非常好用

    禪工作室 13.0.1

    禪工作室 13.0.1

    強大的PHP整合開發環境

    Dreamweaver CS6

    Dreamweaver CS6

    視覺化網頁開發工具

    SublimeText3 Mac版

    SublimeText3 Mac版

    神級程式碼編輯軟體(SublimeText3)

    Springboot怎麼整合Jasypt實現設定檔加密 Springboot怎麼整合Jasypt實現設定檔加密 Jun 01, 2023 am 08:55 AM

    Jasypt介紹Jasypt是一個java庫,它允許開發員以最少的努力為他/她的專案添加基本的加密功能,並且不需要對加密工作原理有深入的了解用於單向和雙向加密的高安全性、基於標準的加密技術。加密密碼,文本,數字,二進位檔案...適合整合到基於Spring的應用程式中,開放API,用於任何JCE提供者...添加如下依賴:com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt好處保護我們的系統安全,即使程式碼洩露,也可以保證資料來源的

    SpringBoot怎麼整合Redisson實現延遲隊列 SpringBoot怎麼整合Redisson實現延遲隊列 May 30, 2023 pm 02:40 PM

    使用場景1、下單成功,30分鐘未支付。支付超時,自動取消訂單2、訂單簽收,簽收後7天未進行評估。訂單超時未評價,系統預設好評3、下單成功,商家5分鐘未接單,訂單取消4、配送超時,推播簡訊提醒…對於延時比較長的場景、即時性不高的場景,我們可以採用任務調度的方式定時輪詢處理。如:xxl-job今天我們採

    怎麼在SpringBoot中使用Redis實現分散式鎖 怎麼在SpringBoot中使用Redis實現分散式鎖 Jun 03, 2023 am 08:16 AM

    一、Redis實現分散式鎖原理為什麼需要分散式鎖在聊分散式鎖之前,有必要先解釋一下,為什麼需要分散式鎖。與分散式鎖相對就的是單機鎖,我們在寫多執行緒程式時,避免同時操作一個共享變數產生資料問題,通常會使用一把鎖來互斥以保證共享變數的正確性,其使用範圍是在同一個進程中。如果換做是多個進程,需要同時操作一個共享資源,如何互斥?現在的業務應用通常是微服務架構,這也意味著一個應用會部署多個進程,多個進程如果需要修改MySQL中的同一行記錄,為了避免操作亂序導致髒數據,此時就需要引入分佈式鎖了。想要實現分

    springboot讀取檔案打成jar包後存取不到怎麼解決 springboot讀取檔案打成jar包後存取不到怎麼解決 Jun 03, 2023 pm 04:38 PM

    springboot讀取文件,打成jar包後訪問不到最新開發出現一種情況,springboot打成jar包後讀取不到文件,原因是打包之後,文件的虛擬路徑是無效的,只能通過流去讀取。文件在resources下publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

    SpringBoot與SpringMVC的比較及差別分析 SpringBoot與SpringMVC的比較及差別分析 Dec 29, 2023 am 11:02 AM

    SpringBoot和SpringMVC都是Java開發中常用的框架,但它們之間有一些明顯的差異。本文將探究這兩個框架的特點和用途,並對它們的差異進行比較。首先,我們來了解一下SpringBoot。 SpringBoot是由Pivotal團隊開發的,它旨在簡化基於Spring框架的應用程式的建立和部署。它提供了一種快速、輕量級的方式來建立獨立的、可執行

    Springboot+Mybatis-plus不使用SQL語句進行多表新增怎麼實現 Springboot+Mybatis-plus不使用SQL語句進行多表新增怎麼實現 Jun 02, 2023 am 11:07 AM

    在Springboot+Mybatis-plus不使用SQL語句進行多表添加操作我所遇到的問題準備工作在測試環境下模擬思維分解一下:創建出一個帶有參數的BrandDTO對像模擬對後台傳遞參數我所遇到的問題我們都知道,在我們使用Mybatis-plus中進行多表操作是極其困難的,如果你不使用Mybatis-plus-join這一類的工具,你只能去配置對應的Mapper.xml文件,配置又臭又長的ResultMap,然後再寫對應的sql語句,這種方法雖然看上去很麻煩,但具有很高的靈活性,可以讓我們

    SpringBoot怎麼自訂Redis實作快取序列化 SpringBoot怎麼自訂Redis實作快取序列化 Jun 03, 2023 am 11:32 AM

    1.自訂RedisTemplate1.1、RedisAPI預設序列化機制基於API的Redis快取實作是使用RedisTemplate範本進行資料快取操作的,這裡開啟RedisTemplate類,查看該類別的源碼資訊publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations,BeanClassLoaderAware{//聲明了value的各種序列化方式,初始值為空@NullableprivateRedisSe

    springboot怎麼取得application.yml裡值 springboot怎麼取得application.yml裡值 Jun 03, 2023 pm 06:43 PM

    在專案中,很多時候需要用到一些配置信息,這些信息在測試環境和生產環境下可能會有不同的配置,後面根據實際業務情況有可能還需要再做修改。我們不能將這些設定在程式碼中寫死,最好是寫到設定檔中,例如可以把這些資訊寫到application.yml檔案中。那麼,怎麼在程式碼裡取得或使用這個位址呢?有2個方法。方法一:我們可以透過@Value註解的${key}即可取得設定檔(application.yml)中和key對應的value值,這個方法適用於微服務比較少的情形方法二:在實際專案中,遇到業務繁瑣,邏

    See all articles