控制台报错:org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
(string 无法绑定 date)
1.写一个类继承Converter
public class DateConvert implements Converter<String, Date> {
@Override
public Date convert(String stringDate) {
SimpleDateFormat simpleDateFormat =null;
if(stringDate.length()==10) {
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
}
else if(stringDate.length()>10)
{
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
try {
return simpleDateFormat.parse(stringDate);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
2.在springmvc.xml中配置这个类
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.fish.controller.DateConvert" />
</list>
</property>
</bean>
<mvc:annotation-driven conversion-service="conversionService" >
<!-- 这段代码时处理responseBody 里面日期类型,不然是一串数字,和上面的代码无关可以加上,用的到 -->
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />
</bean>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>