您好,欢迎访问一九零五行业门户网

SpringBoot @InitBinder注解绑定请求参数的方法是什么

一. 作用作用于controller层中,在controller层的方法执行前执行,主要作用是初始化当前controller层的数据绑定器(或者属性绑定器),帮助完成数据处理和数据绑定。
被该注解修饰的方法会有一个形参webdatabinder,可以帮我们将request请求中的参数处理绑定到javabean中。
二. 前期准备import lombok.data;import java.math.bigdecimal;import java.util.date;@datapublic 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: 'get', success: function (data, status, xhr) { console.log(data); } }); });</script></html>
3.2 controller层stringtrimmereditor和customdateeditor是框架自带的属性处理器
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格式的日期
四. 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: '不明', money: "10000", // yyyy-mm-dd hh:mm:ss格式 birthday: '2022-11-11 12:12:12', // 后台中的list实体类区域 "tablelist[0].id": 1, "tablelist[0].address": '测试address ', "tablelist[0].hobby": '测试hobby ', // yyyy年mm月dd日 hh:mm:ss格式 "tablelist[0].workdate": '2022年11月11日 14:14:14', }; $.ajax({ url: `/test16/receivepost`, type: 'post', data: paramobj, // 表单格式提交 contenttype : 'application/x-www-form-urlencoded;charset=utf-8', // 后端返回给前端的数据类型 datatype: 'json', 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;@datapublic 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;@datapublic 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数类型
因为没有指定转换特定的属性名所对应的数据,所以包括一览中的数据也被成功转换
一览中的字符换的前后空白也被清除,一览中的日期格式的也被成功转换
五. 其他自定义属性编辑器实例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;@datapublic 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: 'get', 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 效果
六. 多个@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); }}
七. 其他用法当前controller继承父类,在父类中使用@initbinder注解来修饰的方法
配合@controlleradvice注解作用于全局
以上就是springboot @initbinder注解绑定请求参数的方法是什么的详细内容。
其它类似信息

推荐信息