mybatis前台傳給帶年月日時分秒的數據給后台,后台接收不到時分秒


框架spring+springMVC+mybatis,

前台給后台傳數據傳不了時分秒,所以用springMVC的注解解決了,記錄一下

controller中如下:

/**
     * 
     * 方法描述 : 使用@InitBinder 標簽對表單數據綁定
     * @param binder
     */
    @InitBinder//spring mvc使用@InitBinder 標簽對表單數據綁定
    public void initBinder(WebDataBinder binder) {//WebDataBinder是用來綁定請求參數到指定的屬性編輯器
        binder.registerCustomEditor(Date.class, new DateConvertEditor("yyyy-MM-dd HH:mm:ss"));

    }
DateConvertEditor
package cn.edu.hbcf.vo;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.apache.commons.lang.StringUtils;
 
/**
 * spring中日期轉換
 * 
 * <pre>
 * &#064;InitBinder
 * public void initBinder(WebDataBinder binder) {
 *     binder.registerCustomEditor(Date.class, new DateConvertEditor());
 *     // binder.registerCustomEditor(Date.class, new
 *     // DateConvertEditor(&quot;yyyy-MM-dd&quot;));
 *     binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
 * }
 * </pre>
 * 
 * 
 * @author LiPenghui
 * @date 2011-8-10 下午1:48:37
 */
public class DateConvertEditor extends PropertyEditorSupport{
    private DateFormat format;
    
    public DateConvertEditor(){
        this.format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }
    
    public DateConvertEditor(String format){
        this.format=new SimpleDateFormat(format);
    }
    
    /** Date-->String **/
    public String getAsText(){
        if(getValue()==null){
            return "";
        }
        return this.format.format(getValue());
    }
    
    /** String-->Date **/
    public void setAsText(String text){
        if(!StringUtils.isNotBlank(text)){
            setValue(null);
        }else{
            try {
                setValue(this.format.parse(text));
            } catch (ParseException e) {
                throw new IllegalArgumentException("不能被轉換的日期字符串,請檢查!", e);
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM