springMVC之@InitBinder的用法

1: 注册属性编辑器
我们在接收参数的时候,对于基础的数据类型,比如接收string,int等类型,springmvc是可以直接处理的,但是对于其他复杂的对象类型,有时候是无法处理的,这时候就需要属性编辑器来进行处理(源数据为string),过程一般就是String->属性编辑器->目标类型。spring为我们提供了一些默认的属性编辑器,如org.springframework.beans.propertyeditors.CustomDateEditor就是其中一个,我们也可以通过继承java.beans.PropertyEditorSuppotr来根据具体的业务来定义自己的属性编辑器。

1.1: 使用系统默认提供的属性编辑器
定义controller并使用@InitBinder注册属性编辑器
这里注册的属性编辑器为org.springframework.beans.propertybeans.CustomDateEditor,作用是根据提供的java.text.SimpleDateFormat将输入的字符串数据转换为java.util.Date类型的数据,核心源码如下:
org.springframework.beans.propertyeditors.CustomDateEditor#setAsText
 public void setAsText(@Nullable String text) throws IllegalArgumentException {
        ...
        else {
            try {
                // 使用用户提供的java.text.SimpeDateFormat来将目标字符串格式化为java.util.Date类型,并通过SetValue方法设置最终值
                setValue(this.dateFormat.parse(text));
            }
            ...
        }
    }

接下来定义类:

@RequestMapping("/myInitBinder0954")
@Controller
public class MyInitBinderController {

    /*
    注册将字符串转换为Date的属性编辑器,该编辑器仅仅对当前controller有效
     */
    @InitBinder
    public void initBinderXXX(WebDataBinder binder) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CustomDateEditor dateEditor = new CustomDateEditor(df, true);
        binder.registerCustomEditor(Date.class, dateEditor);
    }

    // http://localhost:8080/myInitBinder0954/test?date=2020-09-03%2010:17:17会使用在
    // dongshi.controller.initbinder.MyInitBinderController.initBinderXXX注册的属性编辑器转换为,
    // Date类型的
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    @ResponseBody
    public String testFormatData(Date date) {
        Map<String, Object> map = new HashMap<>();
        map.put("date", date);
        return map.toString();
    }
}

访问测试

看到返回了Date的toString的结果,就是说明成功了。
1.2: 使用自定义的属性编辑器
假设我们的需求是这样的,调用方传过来的值是一个_竖线分割的字符串,但是处理的过程使用的是通过_号分割得到的一个String[],我们当然可以在接口内部去处理,但是我们作为专业的屌丝程序员,哈哈哈,还是要用专业一些的手段,这里就可以定义一个将竖线分割的多个字符串转换为String[]的自定义属性编辑器来实现。

自定义属性编辑器
通过继承java.beans.PropertyEditorSupport类并重写其setAdText(String text)方法完成,最后调用setValue(Object Value)方法完成转换后的值的设置。
public class StringToListPropertyEditor extends PropertyEditorSupport {

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        String[] resultArr = null;
        if (!StringUtils.isEmpty(text)) {
            resultArr = text.split("_");
        }
        setValue(resultArr);
    }
}

使用
@RequestMapping("/myStringToList")
@Controller
public class StringToListController {

    @InitBinder
    public void myStringToListBinder(WebDataBinder dataBinder) {
        dataBinder.registerCustomEditor(String[].class, new StringToListPropertyEditor());
    }

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    @ResponseBody
    public String myStringToListTest(String[] strToListArr, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        String result = "_分割字符串转String[]不成功!";
        if (strToListArr != null && strToListArr.length > 0) {
            result = Arrays.asList(strToListArr).toString();
        }
        return result;
    }
}

访问测试

2: 处理带有前缀的form字段
比如这样的场景,在People,Address两个类中都有name字段,但是我们需要在一个表单中录入People和Address的信息,然后在接口中直接通过People,Address两个对象来接收页面的表单数据,但是两个name是无法区分的,一般的做法就是指定一个前缀,然后通过@InitBinder通过调用org.springframework.web.bind.WebDataBinder的setFieldDefaultPrefix(@Nullable String fieldDefaultPrefix)方法,然后在接口中使用注解public @interface ModelAttribute设置要接收的参数的前缀,就可以区分并接收对应的参数了。

2.1: 定义用到的实体
Person
public class People {

    private String name;
    private String age;
    // getter setter toString
}

Address
public class Address {

    private String name;
    private String city;
    
    // getter setter toString
}

2.2: 定义测试使用的表单
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>$Title$</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/myInitBinder0954/test0942" method="post" enctype="multipart/form-data">
    <input type="text" name="people.name" placeholder="人名"><br><br>
    <input type="text" name="people.age" placeholder="人年龄"><br><br>
    <input type="text" name="address.name" placeholder="地址名称"><br><br>
    <input type="text" name="address.city" placeholder="地址所在城市"><br><br>
    <input type="submit" value="提交"/>
</form>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值