Spring MVC 参数依赖注入时,String参数注入为Date类型

来源:互联网 发布:linux用户和组管理命令 编辑:程序博客网 时间:2024/05/22 12:47

在Controller里面增加:

@InitBinderprotected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception {// 对于需要转换为Date类型的属性,使用DateEditor进行处理binder.registerCustomEditor(Date.class, new SpringBindDateEditor());}
public class SpringBindDateEditor extends PropertyEditorSupport {Logger logger=Logger.getLogger(SpringBindDateEditor.class);    private static final DateFormat DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd");    private static final DateFormat TIMEFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm");    public static void main(String[] args) throws Exception {    System.out.println(TIMEFORMAT.parse("2014-10-30 23:50"));;}    private DateFormat dateFormat;    private boolean allowEmpty = true;    public SpringBindDateEditor() {    }    public SpringBindDateEditor(DateFormat dateFormat) {        this.dateFormat = dateFormat;    }    public SpringBindDateEditor(DateFormat dateFormat, boolean allowEmpty) {        this.dateFormat = dateFormat;        this.allowEmpty = allowEmpty;    }    /**     * Parse the Date from the given text, using the specified DateFormat.     */    @Override    public void setAsText(String text) throws IllegalArgumentException {    System.out.println(text);        if (this.allowEmpty && !org.apache.commons.lang3.StringUtils.isNotEmpty(text)) {            // Treat empty String as null value.            setValue(null);        } else {            try {                if(this.dateFormat != null)                    setValue(this.dateFormat.parse(text));                else {                    if(text.contains(":")){                    System.out.println("格式化!"+text);                    Date date=TIMEFORMAT.parse(text);                    System.out.println("Passed ");                        setValue(date);                                            }                    else                        setValue(DATEFORMAT.parse(text));                }            } catch (ParseException ex) {            logger.error("绑定时间出错"+text);                throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);            }        }    }    /**     * Format the Date as String, using the specified DateFormat.     */    @Override    public String getAsText() {        Date value = (Date) getValue();        DateFormat dateFormat = this.dateFormat;        if(dateFormat == null)            dateFormat = TIMEFORMAT;        return (value != null ? dateFormat.format(value) : "");    }}


0 0