目录
一. 作用
二. 前期准备
三. 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{//声明了key、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