彻底解决springMVC无法接受日期类型参数

一、问题

springMVC有一个不叫奇葩的问题,就是如果接受参数是日期(java.util.Date)类型或者参数是包含了(java.util.Date)得POJO将会导致无法进入Controller的方法。没想明白为什么spring作为那么成熟的框架没有兼容这个问题。好了,不废话了,下面讲一下解决办法(不一定是最佳方案,仅供参考)

二、解决办法

1、网上解决办法

其实spring提供了一种解决办法(也是网上查到比价普遍的做法),就是在每一个Controller类里面增加如下方法:

    @InitBinder    

    protected void initBinder(WebDataBinder binder) {    

        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(""), true));    

    }   

这种方法的缺陷:一个比较大的项目的话,可能需要有带时间的日期,也有可能是不带日期的日期,这种办法只能兼用一种日期格式数据

2、我的解决办法

基于上述方法,我查看了spring 这个CustomDateEditor类的源码,其实这个类是提供了日期转换功能。所以我的做法是

第一步:

写一个自己的CustomDateEditor类,让这个类拥有更加强大的日期转换支持,具体代码如下:

import java.beans.PropertyEditorSupport;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.regex.Pattern;

 

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.util.StringUtils;

 

import com.tl.core.exception.FrameworkException;

 

/**

 * 重写spring日期转换器,自定义日期转换器

 * @author zeliangmo

 * mzl 2016-10-7

 */

public class MyCustomDateEditor extends PropertyEditorSupport {

 

protected Logger logger = LoggerFactory.getLogger(this.getClass());

 

 

/**

* Parse the Date from the given text, using the specified DateFormat.

*/

@Override

public void setAsText(String text) throws IllegalArgumentException {

if (!StringUtils.hasText(text)) {

// Treat empty String as null value.

setValue(null);

}

else {

try {

setValue(this.dateAdapter(text));

}

catch (FrameworkException ex) {

ex.printStackTrace();

logger.error("出错日志:"+ex.getMessage());

}

}

}

 

/**

* Format the Date as String, using the specified DateFormat.

*/

@Override

public String getAsText() {

Date value = (Date) getValue();

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

return (value != null ? dateFormat.format(value) : "");

}

 

/**

     * 字符串转日期适配方法

     * @param dateStr 日期字符串

     * @throws FrameworkException 

     */

    public static Date dateAdapter(String dateStr) throws FrameworkException {

    Date date=null;

    String temp=dateStr;//缓存原始数据

    if(!(null==dateStr||"".equals(dateStr))){

    

    //判断是不是日期字符串,如Wed May 28 08:00:00 CST 2014

    if(dateStr.contains("CST")){

    date=new Date(dateStr);

    }else{

    dateStr=dateStr.replace("年", "-").replace("月", "-").replace("日", "").replaceAll("/", "-").replaceAll("\\.", "-").trim();

        String fm="";

        

        //确定日期格式

        if(Pattern.compile("^[0-9]{4}-[0-9]{2}-[0-9]{2}.*").matcher(dateStr).matches()){

        fm = "yyyy-MM-dd";

        }elseif(Pattern.compile("^[0-9]{4}-[0-9]{1}-[0-9]+.*||^[0-9]{4}-[0-9]+-[0-9]{1}.*").matcher(dateStr).matches()){

        fm = "yyyy-M-d";

        }else if(Pattern.compile("^[0-9]{2}-[0-9]{2}-[0-9]{2}.*").matcher(dateStr).matches()){

        fm = "yy-MM-dd";

        }elseif(Pattern.compile("^[0-9]{2}-[0-9]{1}-[0-9]+.*||^[0-9]{2}-[0-9]+-[0-9]{1}.*").matcher(dateStr).matches()){

        fm = "yy-M-d";

        }

        

        //确定时间格式

        if(Pattern.compile(".*[ ][0-9]{2}").matcher(dateStr).matches()){

        fm+= " HH";

        }else if(Pattern.compile(".*[ ][0-9]{2}:[0-9]{2}").matcher(dateStr).matches()){

        fm+= " HH:mm";

        }else if(Pattern.compile(".*[ ][0-9]{2}:[0-9]{2}:[0-9]{2}").matcher(dateStr).matches()){

        fm+= " HH:mm:ss";

        }else if(Pattern.compile(".*[ ][0-9]{2}:[0-9]{2}:[0-9]{2}:[0-9]{0,3}").matcher(dateStr).matches()){

        fm+= " HH:mm:ss:sss";

        }

        

        if(!"".equals(fm)){

        try {

date = new SimpleDateFormat(fm).parse(dateStr);

} catch (ParseException e) {

throw new  FrameworkException("参数字符串“"+dateStr+"”无法被转换为日期格式!");

}

        }

    }

    

    }

    return date;

    }

    

 

 

}

 

第二步:写一个基础Controller,然后全部Controller都继承这个基础Controller就可以解决问题,代码如下:

import java.util.Date;

 

import org.springframework.web.bind.WebDataBinder;

import org.springframework.web.bind.annotation.InitBinder;

 

import com.tl.core.spring.MyCustomDateEditor;

 

/**

 * 所有controller的父类

 */

public class BaseController {

 

 

@InitBinder    

public void initBinder(WebDataBinder binder) {    

    binder.registerCustomEditor(Date.class, new MyCustomDateEditor());    

}  

 

 

}

猜你喜欢

转载自mzllyl.iteye.com/blog/2329020