SpringMVC@InitBinder使用方法

在实际操作中经常会碰到表单中的日期 字符串和Javabean中的日期类型的属性自动转换, 而springMVC默认不支持这个格式的转换,所以必须要手动配置, 自定义数据类型的绑定才能实现这个功能。

比较简单的可以直接应用springMVC的注解@initbinder和spring自带的WebDataBinder类和操作。

解决一种类型

@InitBinder//默认
    public void resolveException(WebDataBinder webDataBinder) {
       //设置转换格式
       SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
       //参数一:转换格式      参数二:是否允许为空字符串
       webDataBinder.registerCustomEditor(Date.class,new CustomDateEditor(sdf,true));
    }

    @RequestMapping("/first")
    public String doFirst(String username, int age, Date birthday) throws Exception {
        //打印转换字符信息
        System.out.println(username);
        System.out.println(age);
        System.out.println(birthday);
        return "doSecond";
    }

自定义属性编辑器

创建类继承PropertiesEditor(属性编辑器)

//自定义属性编辑器
public class MultiController extends PropertiesEditor {
    //手动重写setAsTest方法
    @Override
    public void setAsText(String str) throws IllegalArgumentException {
        //匹配格式
        SimpleDateFormat sdf=getDateFormat(str);
        try {
            //转换Date类型
            Date parse = sdf.parse(str);
            setValue(parse);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    

    private SimpleDateFormat getDateFormat(String str){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日");
        if(Pattern.matches("^\d{4}-\d{1,2}-\d{1,2}$",str)){
            sdf=new SimpleDateFormat("yyyy-MM-dd");
        }
        if(Pattern.matches("^\d{4}/\d{1,2}/\d{1,2}$",str)){
            sdf=new SimpleDateFormat("yyyy/MM/dd");
        }
        if(Pattern.matches("^\d{4}\d{1,2}\d{1,2}$",str)){
            sdf=new SimpleDateFormat("yyyyMMdd");
        }
        return sdf;
    }
}

  

处理器方法

@InitBinder//默认
    public void resolveException(WebDataBinder webDataBinder) {
       //设置转换格式
       SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
       //参数一:转换格式      参数二:自定义属性编辑器
       webDataBinder.registerCustomEditor(Date.class,new MultiController());
    }

    @RequestMapping("/first")
    public String doFirst(String username, int age, Date birthday) throws Exception {
        //打印转换字符信息
        System.out.println(username);
        System.out.println(age);
        System.out.println(birthday);
        return "doSecond";
    }

  

  

原文地址:https://www.cnblogs.com/xuchangqi1/p/8683620.html