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

全局初始化绑定操作                                                                         

@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调试的结果:

猜你喜欢

转载自blog.csdn.net/qq_40594137/article/details/79244690