Spring MVC 傳入Date 為空時 的處理方式

modun1986發表於2011-03-29

使用Spring Mvc 時一直遇到一個問題,就是當前臺傳入一個 Date型別的資料為空時,還進不了Controller 的Action就會丟擲錯誤。


解決方法:

	@InitBinder
	public void InitBinder(WebDataBinder dataBinder)
	{
		dataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
		    public void setAsText(String value) {
		        try {
		            setValue(new SimpleDateFormat("yyyy-MM-dd").parse(value));
		        } catch(ParseException e) {
		            setValue(null);
		        }
		    }

		    public String getAsText() {
		        return new SimpleDateFormat("yyyy-MM-dd").format((Date) getValue());
		    }        

		});
	}
 

相關文章