頁面報錯:
后臺錯誤:
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")
1
2
3
4
5
6
7
8
9
10
|
<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去繼承它
1
2
3
4
|
Springmvc配置文件 < bean class = "org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> < bean class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> |
1
2
3
4
5
6
7
8
9
10
11
|
public class BaseController { @InitBinder public void initBinder(WebDataBinder binder) { /** * 第一種方式:使用WebDataBinder注冊一個自定義的編輯器,編輯器是日期類型 * 使用自定義的日期編輯器,日期格式:yyyy-MM-dd,第二個參數為是否為空 true代表可以為空 */ binder.registerCustomEditor(Date. class , new CustomDateEditor( new SimpleDateFormat( "yyyy-MM-dd" ), true )); } } |
或者使用下面的方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
public class BaseController { @InitBinder public void initBinder(WebDataBinder binder) { /** * 方式二:使用WebDataBinder注冊一個自定義的編輯器,編輯器是日期類型 * 使用屬性編輯器實現:重載setAsText,getAsText */ binder.registerCustomEditor(Date. class , new PropertyEditorSupport() { @Override public String getAsText() { return new SimpleDateFormat( "yyyy-MM-dd" ) .format((Date) getValue()); } @Override public void setAsText(String text) { try { setValue( new SimpleDateFormat( "yyyy-MM-dd" ).parse(text)); } catch (Exception e) { e.printStackTrace(); setValue( null ); } } }); } } |
以上這篇解決springmvc關于前臺日期作為實體類對象參數類型轉換錯誤的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。