spring mvc使用@InitBinder标签对表单数据绑定

        在SpringMVC中,bean中定义了Date,double等类型,如果没有做任何处理的话,日期以及double都无法绑定。

        解决的办法就是使用spring mvc提供的@InitBinder标签。

        在我的项目中是在BaseController中增加方法initBinder,并使用注解@InitBinder标注,那么spring mvc在绑定表单之前,都会先注册这些编辑器,当然你如果不嫌麻烦,你也可以单独的写在你的每一个controller中。剩下的控制器都继承该类。spring自己提供了大量的实现类,诸如CustomDateEditor ,CustomBooleanEditor,CustomNumberEditor等许多,基本上够用。

        当然,我们也可以不使用他自己自带这些编辑器类,下面我们自己去构造几个。

import org.springframework.beans.propertyeditors.PropertiesEditor;

public class DoubleEditor extends PropertiesEditor {  
    @Override  
    public void setAsText(String text) throws IllegalArgumentException {  
        if (text == null || text.equals("")) {  
            text = "0";  
        }  
        setValue(Double.parseDouble(text));  
    }  
  
    @Override  
    public String getAsText() {  
        return getValue().toString();  
    }  
}
import org.springframework.beans.propertyeditors.PropertiesEditor;

public class IntegerEditor extends PropertiesEditor {  
    @Override  
    public void setAsText(String text) throws IllegalArgumentException {  
        if (text == null || text.equals("")) {  
            text = "0";  
        }  
        setValue(Integer.parseInt(text));  
    }  
  
    @Override  
    public String getAsText() {  
        return getValue().toString();  
    }  
}
import org.springframework.beans.propertyeditors.PropertiesEditor;

public class FloatEditor extends PropertiesEditor {  
    @Override  
    public void setAsText(String text) throws IllegalArgumentException {  
        if (text == null || text.equals("")) {  
            text = "0";  
        }  
        setValue(Float.parseFloat(text));  
    }  
  
    @Override  
    public String getAsText() {  
        return getValue().toString();  
    }  
}
import org.springframework.beans.propertyeditors.PropertiesEditor;

public class LongEditor extends PropertiesEditor {  
    @Override  
    public void setAsText(String text) throws IllegalArgumentException {  
        if (text == null || text.equals("")) {  
            text = "0";  
        }  
        setValue(Long.parseLong(text));  
    }  
  
    @Override  
    public String getAsText() {  
        return getValue().toString();  
    }  
}
import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.util.StringUtils;

public class CustomDateEditorWapper extends PropertyEditorSupport {
    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private final boolean allowEmpty;

    /**
     * 是否允许为空
     * @param allowEmpty
     */
    public CustomDateEditorWapper(boolean allowEmpty) {
        this.allowEmpty = allowEmpty;
    }

    /**
     * 根据格式绑定数据
     */
    public void setAsText(String text) throws IllegalArgumentException {
        if (this.allowEmpty && !StringUtils.hasText(text)) {
            setValue(null);
        } else if (text.indexOf("1") == 0 && text.length() == 13 && text.indexOf("-") < 0) {
            //日期传Long的转换
            setValue(new Date(Long.parseLong(text)));
        } else {
            setValue(DateUtils.parseTime(text));
        }
    }

    public String getAsText() {
        Date value = (Date) getValue();
        return (value != null ? this.dateFormat.format(value) : "");
    }
}

        在BaseController中。

@InitBinder
protected final void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
    // 在这里注册自定义的PropertyEditor
//    binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
    binder.registerCustomEditor(java.util.Date.class, new CustomDateEditorWapper(true));
//      binder.registerCustomEditor(int.class, new CustomNumberEditor(int.class, true));  
    binder.registerCustomEditor(int.class, new IntegerEditor());  
    binder.registerCustomEditor(long.class, new LongEditor());  
    binder.registerCustomEditor(double.class, new DoubleEditor());  
    binder.registerCustomEditor(float.class, new FloatEditor()); 
}

@InitBinder
public void initBinder(WebDataBinder binder) {
    // 设置List的最大长度
    binder.setAutoGrowCollectionLimit(5000);
}

        看到这里的CustomDateEditorWapper没?编辑器类直接继承PropertyEditorSupport也可以的。

 

        附上日志处理的工具类DateUtils:

import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * 日期工具类 
 */
public class DateUtils {

    private static java.util.Date formatDate(String split, String date, SimpleDateFormat df, int length)
            throws ParseException {
        
        String formatStr = "yyyy-MM-dd";
        if (length == 5) {
            if (date.indexOf(split) == length - 1) {// 2008-
                formatStr = "yyyy";
                date = date.substring(0, 4);
            } else {
                formatStr = "yyyy-MM";// 2008-01
            }
        } else if (length >= 6 && length <= 7) {// 2008-1 -- 2008-01
            formatStr = "yyyy-MM";
        } else if (length >= 8 && length <= 9) {
            if (date.lastIndexOf(split) == length - 1) { // 2008-12-
                formatStr = "yyyy-MM";
                date = date.substring(0, length - 1);
            } else {
                formatStr = "yyyy-MM-dd";// 2008-1-1 -- 2008-01-01
            }
        } else if (length >= 10 && length <= 11) {
            if (date.indexOf(" ") > -1 && date.indexOf(" ") < length - 1) {
                formatStr = "yyyy-MM-dd HH";// 2008-1-1 1 --
            } else {
                formatStr = "yyyy-MM-dd";// "2008-01-01"中间无空格
            }
        } else if (length >= 12 && length <= 13) {
            if (date.indexOf(":") > -1 && date.indexOf(":") < length - 1) {
                formatStr = "yyyy-MM-dd HH:mm";// 2008-1-1 1:1 --
                                               // 2008-1-1 1:01
            } else {
                formatStr = "yyyy-MM-dd HH";// 2008-01-01 01 中间有空格
            }
        } else if (length >= 14 && length <= 16) {
            int lastIndex = date.lastIndexOf(":");
            if (date.indexOf(":") > -1 && lastIndex < length - 1 && date.indexOf(":") != lastIndex) {
                formatStr = "yyyy-MM-dd HH:mm:ss";// 2008-1-1 1:1:1
                                                  // -- 2008-01-01
                                                  // 1:1:1 中间有两个冒号
                if (lastIndex < length - 1 - 2) {
                    date = date.substring(0, lastIndex + 3);
                }
            } else if (date.indexOf(":") > -1 && lastIndex < length - 1 && date.indexOf(":") == lastIndex) {
                formatStr = "yyyy-MM-dd HH:mm";// 2008-01-01 1:1 --
                                               // 2008-01-01
                                               // 01:01中间只有一个冒号
            } else if (date.indexOf(":") > -1 && lastIndex == length - 1 && date.indexOf(":") == lastIndex) {
                formatStr = "yyyy-MM-dd HH";// 2008-01-01 01:
                                            // 只有一个冒号在末尾
                date = date.substring(0, length - 1);
            }
        } else if (length == 17) {
            int lastIndex = date.lastIndexOf(":");
            if (lastIndex < length - 1) {
                formatStr = "yyyy-MM-dd HH:mm:ss";// 2008-1-1 1:1:1
                                                  // -- 2008-01-01
                                                  // 1:1:1 中间有两个冒号
                if (lastIndex < length - 1 - 2) {
                    date = date.substring(0, lastIndex + 3);
                }
            } else if (lastIndex == length - 1) {
                formatStr = "yyyy-MM-dd HH:mm";// 2008-01-01 1:1 --
                                               // 2008-01-01
                                               // 01:01中间只有一个冒号
                date = date.substring(0, length - 1);
            }
        } else if (length >= 18) {
            formatStr = "yyyy-MM-dd HH:mm:ss";// 2008-1-1 1:1:1 --
                                              // 2008-01-01
                                              // 01:01:01 有两个冒号
            int lastIndex = date.lastIndexOf(":");
            if (lastIndex < length - 1 - 2) {
                date = date.substring(0, lastIndex + 3);
            }
        }

        formatStr = formatStr.replace("-", split);
        df.applyPattern(formatStr);

        return df.parse(date);
    }
    
    /**
     * 将常用时间字符串转换为时间对象
     * @param String
     * @return java.util.Date
     * @throws Exception 
     */
    public static java.util.Date parseTime(String date) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat();
        java.util.Date rtnDate = null;
        if (date == null || date.trim().equals("") || date.trim().equals("null"))
            return rtnDate;
        try {
            date = date.trim();
            int length = date.length();
            if (date.indexOf("-") != -1) {
                if (length == 5) {
                    if (date.indexOf("-") == length - 1) {//2008- 
                        df.applyPattern("yyyy");
                        date = date.substring(0, 4);
                        rtnDate = df.parse(date);
                    } else {
                        df.applyPattern("yyyy-MM");//2008-01
                        rtnDate = df.parse(date);
                    }
                } else if (length >= 6 && length <= 7) {//2008-1 -- 2008-01
                    df.applyPattern("yyyy-MM");
                    rtnDate = df.parse(date);
                } else if (length >= 8 && length <= 9) {
                    if (date.lastIndexOf("-") == length - 1) { //2008-12-
                        df.applyPattern("yyyy-MM");
                        date = date.substring(0, length - 1);
                        rtnDate = df.parse(date);
                    } else {
                        df.applyPattern("yyyy-MM-dd");//2008-1-1 -- 2008-01-01
                        rtnDate = df.parse(date);
                    }
                } else if (length >= 10 && length <= 11) {
                    if (date.indexOf(" ") > -1 && date.indexOf(" ") < length - 1) {
                        df.applyPattern("yyyy-MM-dd HH");//2008-1-1 1 -- 2008-1-1 11 中间有空格
                        rtnDate = df.parse(date);
                    } else {
                        df.applyPattern("yyyy-MM-dd");//"2008-01-01"中间无空格
                        rtnDate = df.parse(date);
                    }
                } else if (length >= 12 && length <= 13) {
                    if (date.indexOf(":") > -1 && date.indexOf(":") < length - 1) {
                        df.applyPattern("yyyy-MM-dd HH:mm");//2008-1-1 1:1  -- 2008-1-1 1:01 中间有冒号
                        rtnDate = df.parse(date);
                    } else {
                        df.applyPattern("yyyy-MM-dd HH");//2008-01-01 01 中间有空格
                        rtnDate = df.parse(date);
                    }
                } else if (length >= 14 && length <= 16) {
                    int lastIndex = date.lastIndexOf(":");
                    if (date.indexOf(":") > -1 && lastIndex < length - 1 && date.indexOf(":") != lastIndex) {
                        df.applyPattern("yyyy-MM-dd HH:mm:ss");//2008-1-1 1:1:1  -- 2008-01-01 1:1:1 中间有两个冒号
                        if (lastIndex < length - 1 - 2) {
                            date = date.substring(0, lastIndex + 3);
                        }
                        rtnDate = df.parse(date);
                    } else if (date.indexOf(":") > -1 && lastIndex < length - 1 && date.indexOf(":") == lastIndex) {
                        df.applyPattern("yyyy-MM-dd HH:mm");//2008-01-01 1:1  -- 2008-01-01 01:01中间只有一个冒号
                        rtnDate = df.parse(date);
                    } else if (date.indexOf(":") > -1 && lastIndex == length - 1 && date.indexOf(":") == lastIndex) {
                        df.applyPattern("yyyy-MM-dd HH");//2008-01-01 01: 只有一个冒号在末尾
                        date = date.substring(0, length - 1);
                        rtnDate = df.parse(date);
                    }
                } else if (length == 17) {
                    int lastIndex = date.lastIndexOf(":");
                    if (lastIndex < length - 1) {
                        df.applyPattern("yyyy-MM-dd HH:mm:ss");//2008-1-1 1:1:1  -- 2008-01-01 1:1:1 中间有两个冒号
                        if (lastIndex < length - 1 - 2) {
                            date = date.substring(0, lastIndex + 3);
                        }
                        rtnDate = df.parse(date);
                    } else if (lastIndex == length - 1) {
                        df.applyPattern("yyyy-MM-dd HH:mm");//2008-01-01 1:1  -- 2008-01-01 01:01中间只有一个冒号
                        date = date.substring(0, length - 1);
                        rtnDate = df.parse(date);
                    }
                } else if (length >= 18) {
                    df.applyPattern("yyyy-MM-dd HH:mm:ss");//2008-1-1 1:1:1  -- 2008-01-01 01:01:01 有两个冒号
                    int lastIndex = date.lastIndexOf(":");
                    if (lastIndex < length - 1 - 2) {
                        date = date.substring(0, lastIndex + 3);
                    }
                    rtnDate = df.parse(date);
                }
            //对时间格式中以/为分隔符的日期做处理
            } else if (date.indexOf("/") != -1) {
                rtnDate = formatDate("/", date, df, length);
            } else if (length == 4) {
                df.applyPattern("yyyy");
                rtnDate = df.parse(date);
            } else if (length >= 5 && length <= 6) {
                df.applyPattern("yyyyMM");
                rtnDate = df.parse(date);
            } else if (length >= 7 && length <= 8) {
                df.applyPattern("yyyyMMdd");
                rtnDate = df.parse(date);
            } else if (length >= 9 && length <= 10) {
                df.applyPattern("yyyyMMddHH");
                rtnDate = df.parse(date);
            } else if (length >= 11 && length <= 12) {
                df.applyPattern("yyyyMMddHHmm");
                rtnDate = df.parse(date);
            } else if (length >= 13 && length <= 14) {
                df.applyPattern("yyyyMMddHHmmss");
                rtnDate = df.parse(date);
            } else if (length >= 15) {
                df.applyPattern("yyyyMMddHHmmss");
                date = date.substring(0, 14);
                rtnDate = df.parse(date);
            }
        } catch (Exception ex) {
            throw ex;
        }
        return rtnDate;
    }
}

 

参考资料:http://blog.csdn.net/axin66ok/article/details/17938095

猜你喜欢

转载自bijian1013.iteye.com/blog/2282426