التحقق من صحة الربيع: لا يمكن التحويل من سلسلة حتى الآن
-
29-09-2019 - |
سؤال
أقوم ببعض التحقق من صحة نموذج الربيع ، لكنني أحصل على:
Failed to convert property value of type 'java.lang.String' to required type 'ja
va.util.Date' for property 'birthdate'; nested exception is java.lang.Illega
lStateException: Cannot convert value of type [java.lang.String] to required typ
e [java.util.Date] for property 'birthdate': no matching editors or conversi
on strategy found
ومع ذلك ، في نموذج ModelAttribute لدي:
@NotNull
@Past
@DateTimeFormat(style="S-")
private Date birthdate;
اعتقدت أن DateTimeFormat كان مسؤولاً عن هذا؟
أنا أستخدم Hibernate-Validator 4.0.
المحلول
هناك فرصة ستضطر إلى استخدام التسجيل أ CustomDateEditor
في وحدة التحكم (أجهزة التحكم) الخاصة بك للتحويل من سلسلة إلى تاريخ. تسير طريقة المثال أدناه في وحدة التحكم الخاصة بك ، ولكن سيتعين عليك تغيير تنسيق التاريخ لمطابقة كل ما تستخدمه.
@InitBinder
public void initBinder(WebDataBinder binder) {
CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true);
binder.registerCustomEditor(Date.class, editor);
}
نصائح أخرى
لكي تستخدم @DateTimeFormat
تحتاج إلى التثبيت FormattingConversionServiceFactoryBean
. <mvc:annotation-driven>
هل هذا الأمر ضمنيًا ، ولكن إذا لم تتمكن من استخدامه ، فأنت بحاجة إلى شيء مثل هذا:
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />
<bean id="annotationMethodHandlerAdapter"
class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean id="configurableWebBindingInitializer"
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="validator"><ref bean="validator"/>
<proeprty name = "conversionService" ref = "conversionService" />
</bean>
</property>
</bean>
لا تنتمي إلى StackOverflow