框架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> * @InitBinder * public void initBinder(WebDataBinder binder) { * binder.registerCustomEditor(Date.class, new DateConvertEditor()); * // binder.registerCustomEditor(Date.class, new * // DateConvertEditor("yyyy-MM-dd")); * 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); } } } }