Spring MVC(学习笔记六)控制器的注解(五) -之全局初始化绑定操作(@InitBinder)

本文介绍如何使用 Spring MVC 中的 @InitBinder 注解来实现数据绑定和自定义转换器。通过示例展示了如何创建全局的数据绑定处理器,以及如何为特定类型注册自定义编辑器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

全局初始化绑定操作                                                                         

@InitBinder  定义初始化的方法:不能有返回值,它必须盛名为void。

WebDataBinder:是用来绑定请求参数到指定的属性编辑器.由于前台传到controller里的值是String类型的,当往Model里Set这个值的时候,如果set的这个属性是个对象,Spring就会去找到对应的editor进行转换,然后再SET进去。

首先在HandlerMethodArgumentController(访问路径:/hmac)类编写一个处理方法:

@PostMapping(value = "sib")
public String setInitBinder(Date time){
    System.out.println(time);//输出的结果:Fri Nov 11 00:00:00 CST 2011
    return "index";
}
再定义一个全局处理的类:GlobalControllerAdiviceController:
@ControllerAdvice
public class GlobalControllerAdiviceController {
    //初始化绑定操作【全局形式】
    @InitBinder
    public void dataBind(WebDataBinder binder){
        //设置的格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        ///給指定类型注册类型转换器操作
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }
}
最后在编写index.jsp页面:
<h1>binder</h1>
<form action="${pageContext.request.contextPath}/hmac/sib" method="post">
    <input type="text" name="time" value="2011-11-11">
    <input type="submit" value="sub">
</form>

自定义转换配置                                                                                                                               

 1. 定义转换类 (继承:PropertyEditorSupport)
  setAsText :设置文本操作

  setValue: 设置值

//包名:editor
public class UserPropertyEditor extends PropertyEditorSupport {
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (!StringUtils.isEmpty(text)){

            //获取内容,并进行转换操作
            String[] userText=text.split(":");
            User user=new User();
            user.setId(Integer.parseInt(userText[0]));
            user.setName(userText[1]);
            user.setPwd(userText[2]);

            //设置值
            setValue(user);
        }else{
            //...
        }
    }
}

 2. 注册转换操作:全局处理类:GlobalControllerAdiviceController

@ControllerAdvice
public class GlobalControllerAdiviceController {
    /**
     * 初始化绑定操作【全局形式】
     * @ControllerAdvice(对controller请求进行处理操作(@ReuqestMapping))+@InitBinder(自定义绑定操作)+WebDataBinder(web数据绑定对象)
     */
    @InitBinder
    public void dataBind(WebDataBinder binder){
        //注册自定义转换类型
        binder.registerCustomEditor(User.class,new UserPropertyEditor());
    }
}

编写index.jsp页面:
<h1>customer binder</h1>
<form action="${pageContext.request.contextPath}/hmac/scb" method="post">
    <input type="text" name="us" value="1001:mj:test">
    <input type="submit" value="sub">
</form>

我debug调试的结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值