SpringMVC配置字符串绑定日期对象

1. controller中局部绑定

步骤一:编写转换器,前端字符串转化为日期对象

public class DateEditor extends PropertyEditorSupport {

 private final DateFormat dateFormat;
 private final boolean allowEmpty;
 private final int exactDateLength;

 /**
  * Create a new DateEditor instance, using the given DateFormat
  * for parsing and rendering.
  */
 public DateEditor(DateFormat dateFormat, boolean allowEmpty) {
  this.dateFormat = dateFormat;
  this.allowEmpty = allowEmpty;
  this.exactDateLength = -1;
 }

 /**
  * Create a new DateEditor instance, using the given DateFormat
  * for parsing and rendering.
  */
 public DateEditor(DateFormat dateFormat, boolean allowEmpty, int exactDateLength) {
  this.dateFormat = dateFormat;
  this.allowEmpty = allowEmpty;
  this.exactDateLength = exactDateLength;
 }

 /**
  * Parse the Date from the given text, using the specified DateFormat.
  */
 @Override
 public void setAsText(String text) throws IllegalArgumentException {
  if (this.allowEmpty && !StringUtils.hasText(text)) {
   // Treat empty String as null value.
   setValue(null);
  }
  else if (text != null && this.exactDateLength >= 0 && text.length() != this.exactDateLength) {
   throw new IllegalArgumentException(
     "Could not parse date: it is not exactly" + this.exactDateLength + "characters long");
  }
  else {
   try {
    long dateLong = Long.parseLong(text);
    text = this.dateFormat.format(new Date(dateLong));
   } catch (Exception ex) {
    // 输入文本非long型
   }
   try {
    setValue(this.dateFormat.parse(text));
   } catch (ParseException ex) {
    setValue(null);
   }
  }
 }

 /**
  * Format the Date as String, using the specified DateFormat.
  */
 @Override
 public String getAsText() {
  Date value = (Date) getValue();
  return (value != null ? this.dateFormat.format(value) : "");
 }

}

步骤二:在要转化的controller中注册

/**
 * 绑定日期格式
 *
 * @param res 资源请求
 * @param binder 资源绑定
 */
@InitBinder
public void initBinder(HttpServletRequest res, WebDataBinder binder) {
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 binder.registerCustomEditor(Date.class, new DateEditor(sdf, false));
}

2. 配置全局日期转换器

新版的Spring3.1.x之后,配置全局转换器有所不同。

步骤一:编写全局日期转换器

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;
public class DateConverter implements Converter<String, Date> {

 private static final SimpleDateFormat DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd");  
    private static final SimpleDateFormat TIMEFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat TIMEFORMAT2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

 @Override
 public Date convert(String source) {
//   SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

  if (!StringUtils.hasText(source)) {
   return null;
  }

  try {
   SimpleDateFormat dateFormat = getDateFormat(source);
   dateFormat.setLenient(false);
   return dateFormat.parse(source);
  } catch (ParseException e) {
   e.printStackTrace();
  }catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

 /**
  * 功能:用本地的三种日期格式实例化出DateFormat对象
  *
  * @param value 待解析的值
  * @return DateFormat对象
  */
 private SimpleDateFormat getDateFormat(String value){
  SimpleDateFormat dateFormat = null;

  Pattern patter = null;
  Matcher matcher = null;
  String formatter = null;

  try{
   // ^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$
   // yyyy-mm-dd
   patter = Pattern.compile("^\\d{4}\\-\\d{1,2}\\-\\d{1,2}$");
   matcher = patter.matcher(value);
   if (matcher.matches()) {
    dateFormat = DATEFORMAT;
    formatter = "yyyy-mm-dd";
    //System.out.println("yyyy-mm-dd");
    return dateFormat;
   }

   // yyyy-MM-dd HH:mm:ss
   patter = Pattern.compile("^\\d{4}\\-\\d{1,2}\\-\\d{1,2}\\s{1}\\d{1,2}:\\d{1,2}:\\d{1,2}$");
   matcher = patter.matcher(value);
   if (matcher.matches()) {
    dateFormat = TIMEFORMAT;
    formatter = "yyyy-MM-dd HH:mm:ss";
    //System.out.println("yyyy-MM-dd HH:mm:ss");
    return dateFormat;
   }

   // yyyy/MM/dd HH:mm:ss
   patter = Pattern.compile("^\\d{4}\\/\\d{1,2}\\/\\d{1,2}\\s{1}\\d{1,2}:\\d{1,2}:\\d{1,2}$"); // yyyy-MM-dd HH:mm:ss
   matcher = patter.matcher(value);
   if (matcher.matches()) {
    dateFormat = TIMEFORMAT2;
    formatter = "yyyy/MM/dd HH:mm:ss";
    //System.out.println("yyyy/MM/dd HH:mm:ss");
    return dateFormat;
   }

   if (!StringUtils.hasText(formatter)) {
    throw new IllegalArgumentException("cannot parse value[" + value + "] to date");
   }
  }catch(PatternSyntaxException se){
   throw se;
  }


  return dateFormat;
 }

步骤二:在配置文件中进行配置

(1) <mvc:annotation-driven />中配置中的AnnotationMethodHandlerAdapter已经配置了webBindingInitializer

我们可以通过设置其属性conversionService来实现自定义类型转换

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">    
 <property name="converters">    
  <list>    
   <bean class="com.doje.XXX.web.DateConverter" />     <!-- 转换器实现类 -->
  </list>    
 </property>    
</bean>  
(2) 修改spring service context xml配置文件中的annotation-driven,增加属性conversion-service指向新增的conversionService bean
<mvc:annotation-driven conversion-service="conversionService" />  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值