Spring mvc 使用PropertyEditor进行数据转换

        项目中遇到一个对timestamp 进行数据转换问题,spring mvc 提供了

        initBinder的方法来处理这类型的问题,下面记录一下。

        controller 注册转换的PropertyEditor:

        

@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转换

这个过程会针对TimeStamp类型的类进行使用对用的转换器

参考http://www.iteye.com/blogs/subjects/springmvc-tattle 这个的博客,有更多springmvc介绍


你可能感兴趣的:(springMVC,数据绑定)