springmvc關於前台日期作為實體類對象參數類型轉換錯誤,springmvc實體
頁面報錯:
後台錯誤:
Field error in object 'user' on field 'birthday': rejected value [2013-06-24]; codes [typeMismatch.user.birthday,typeMismatch.birthday,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.birthday,birthday]; arguments []; default message [birthday]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'birthday'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.util.Date for value '2013-06-24'; nested exception is java.lang.IllegalArgumentException]
解決方案1:在對應的實體類屬性上加入 @DateTimeFormat(pattern = "yyyy-MM-dd")
解決方案2:不使用 <mvc:annotation-driven/>註解
使用 DefaultAnnotationHandlerMapping 和 AnnotationMethodHandlerAdapter 註解驅動配置
在對應的實體類屬性上加入 @DateTimeFormat(pattern = "yyyy-MM-dd")
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="webBindingInitializer"> <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"> <property name="conversionService"> <bean class="org.springframework.format.support.FormattingConversionServiceFactoryBean"/> </property> </bean> </property> </bean>
3、使用 @InitBinder註解,註冊一個父類Controller(BaseController),其他Controller去繼承它
Springmvc設定檔
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
1 public class BaseController { 2 @InitBinder 3 public void initBinder(WebDataBinder binder) { 4 /** 5 * 第一種方式:使用WebDataBinder註冊一個自訂的編輯器,編輯器是日期類型 6 * 使用自訂的日期編輯器,日期格式:yyyy-MM-dd,第二個參數為是否為空白 true代表可以為空白 7 */ 8 binder.registerCustomEditor(Date.class, new CustomDateEditor( 9 new SimpleDateFormat("yyyy-MM-dd"), true));10 }11 }
或者使用下面的方式
1 public class BaseController { 2 @InitBinder 3 public void initBinder(WebDataBinder binder) { 4 /** 5 * 方式二:使用WebDataBinder註冊一個自訂的編輯器,編輯器是日期類型 6 * 使用屬性編輯器實現:重載setAsText,getAsText 7 */ 8 binder.registerCustomEditor(Date.class, new PropertyEditorSupport() { 9 10 @Override11 public String getAsText() {12 return new SimpleDateFormat("yyyy-MM-dd")13 .format((Date) getValue());14 }15 16 @Override17 public void setAsText(String text) {18 try {19 setValue(new SimpleDateFormat("yyyy-MM-dd").parse(text));20 } catch (Exception e) {21 e.printStackTrace();22 setValue(null);23 }24 }25 26 });27 }28 }