SpringMVC日期类型自动转换的处理

1、前言
表单中有一个日期字段,准入日期accessDate


<div id="accessDate_div" class="col-xs-4">
    "text" class="form-control" 
    id="accessDate" name="accessDate" >
div>
$("#accessDate").datebox();

model:

@SuppressWarnings("serial")
public class DeviceSupplierAccess extends BaseEntity{
/**
  * 准入日期
  */
private Date accessDate;

}

controller:

@ResponseBody
@RequestMapping("/saveOrUpdate")
public Json saveOrUpdate(DeviceSupplierAccess  
     dsAccess){
     Json json = new Json();
     try {
         System.out.println("accessDate:" + dsAccess.getAccessDate());

         json.setSuccess(true);
     } catch (Exception e) {
         json.setSuccess(false);
     }
     return json;
}

控制台打印信息:

[2017-07-20 17:32:15] org.hibernate.hql.internal.QueryTranslatorFactoryInitiator.initiateService(QueryTranslatorFactoryInitiator.java:47) 
 HHH000397: Using ASTQueryTranslatorFactory

accessDate:null

2、处理方式
在BaseController中添加

@InitBinder
public void initBinder(ServletRequestDataBinder binder) {
    /**
      * 自动转换日期类型的字段格式
      */
    binder.registerCustomEditor(Date.class, new SpecialDateEditor());
}

SpecialDateEditor.java代码如下:

package com.core.utils;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SpecialDateEditor extends PropertyEditorSupport {

    private final Logger logger = LoggerFactory.getLogger(getClass());  

    @Override  
    public void setAsText(String text) throws IllegalArgumentException {  
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        Date date = null;  
        try {  
            //防止空数据出错  
            if(StringUtils.notNull(text)){  
                date = format.parse(text);  
            }  
        } catch (ParseException e) {  
            format = new SimpleDateFormat("yyyy-MM-dd");  
            try {  
                date = format.parse(text);  
            } catch (ParseException e1) {  
                format = new SimpleDateFormat("yyyy-MM");  

                try{  
                    date = format.parse(text);  
                }catch (Exception e2) {  
                    logger.error("自动绑定日期数据出错", e);  
                }  
            }  
        }  
        setValue(date);  
    }  
}

再看控制台打印信息:

[2017-07-20 17:48:01] org.hibernate.hql.internal.QueryTranslatorFactoryInitiator.initiateService(QueryTranslatorFactoryInitiator.java:47) 
 HHH000397: Using ASTQueryTranslatorFactory

accessDate:Thu Jul 06 00:00:00 CST 2017

OK,

注:
BaseController还可以用别外一种写法:

@InitBinder  
public void initBinder(WebDataBinder b) {  
   b.registerCustomEditor(Date.class, new SpecialDateEditor());  
} 

你可能感兴趣的:(springmvc)