后端javabean中可能有date之类的属性,当前端参数绑定时;由于前端传入的是String,所以会导致异常出现,导致参数绑定失败。这时我们就需要自定义转换器:
xml配置:
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.cover.DataConver"/> </list> </property> </bean>
自定义转换类,需要实现convetor类:
public class DataConver implements Converter<String,Date> { @Override public Date convert(String s) { //将页面传递的string类型的时间字符串,转化成javabean 的date对象 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date time = null; try { time = simpleDateFormat.parse(s); } catch (ParseException e) { e.printStackTrace(); } return time; } }这样在参数绑定时,就会spring就会运用上面的转换,将String转化为date。