Spring mvc 使用PropertyEditor進行數據轉換

        項目中遇到一個對timestamp 進行數據轉換問題,spring mvc 提供了 java

        initBinder的方法來處理這類型的問題,下面記錄一下。 spring

        controller 註冊轉換的PropertyEditor: mvc

        

@Override
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		// TODO Auto-generated method stub
		//yyy/mmdd yyy-mm-dd yy-mm-dd HH:mm:ss
		binder.registerCustomEditor(Timestamp.class,
				new TimeStampPropertyEditor());
		super.initBinder(request, binder);
	}


編寫對於TimeStampPropertyEditor 的轉換操做



public class TimeStampPropertyEditor extends PropertyEditorSupport {

	private String pattern = "yyyy-MM-dd HH:mm:ss.S";

	private String[] formater_pattern = new String[] { "yyyy-MM-dd HH:mm:ss.S",
			"yyyy-MM-dd HH:mm:ss" };

	/**
	 * 
	 */
	public TimeStampPropertyEditor() {
		// TODO Auto-generated constructor stub
	}

	public TimeStampPropertyEditor(String pattern) {
		// TODO Auto-generated constructor stub
		this.pattern = pattern;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
	 */
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (StringUtils.isEmpty(text)) {
			setValue(null);
		} else {
			try {
				Date date = DateUtils.parseDate(text, formater_pattern);
				Timestamp timestamp = new Timestamp(date.getTime());
				//				設置轉換完的值
				setValue(timestamp);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				setValue(null);
			}
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.beans.PropertyEditorSupport#getAsText()
	 */
	@Override
	public String getAsText() {
		// TODO Auto-generated method stub
		//	獲取model的值
		Timestamp value = (Timestamp) getValue();
		if (value == null) {
			return "";
		} else {
			try {
				Date date = new Date(value.getTime());
				String str = DateFormatUtils.format(date, pattern);
				return str;
			} catch (Exception e) {
				return "";
			}
		}

	}

}


ok,當pages-->controller-->對應method-->initbinder-->bind轉換 ide

這個過程會針對TimeStamp類型的類進行使用對用的轉換器 this

參考http://www.iteye.com/blogs/subjects/springmvc-tattle 這個的博客,有更多springmvc介紹 code

相關文章
相關標籤/搜索