springMVC的注解@InitBinder

时间:2019-10-09
本文章向大家介绍springMVC的注解@InitBinder,主要包括springMVC的注解@InitBinder使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.在带有@Controller注解的class类中的带有@InitBinder注解的方法

   被此注解的方法可以对WebDataBinder初始化,webDataBinder是用于form表单到方法的数据绑定,WebDataBinder是用来绑定请求参数到指定的属性编辑器。

2.对实体类中的某个属性绑定进行设置是否要求绑定

3.对于前后端交互时,今天就遇到一个日期格式化问题。

由于前端传回来的参数中日期是String类型,而我们需要的是Date类型,spring MVC不支持对String类型日期格式转换Date类型。这里就需要这个带有@InitBinder注解的方法中将传回来的日期参数进行格式化操作。操作代码如下:

    @InitBinder
    public void initBinder(WebDataBinder binder) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

原文地址:https://www.cnblogs.com/Fantastic-Code/p/11643067.html