SpringMVC 配置类型转换

第一种方式:

在需要转换的属性上面添加注解 @DateTimeFormat(pattern="yyyy-MM-dd")

@DateTimeFormat(pattern="yyyy-MM-dd")
private Date myDate;//方式一

但是不起作用

第二种方式:在springmvc的配置文件中添加如下配置

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
  <property name="converters">
    <set>
      <bean class="org.qh.springmvc.util.MyConverter" p:datePattern="yyyy-MM-dd"/>
      <bean class="org.qh.springmvc.util.UserConverter" p:datePattern="yyyy-MM-dd"/>
    </set>
  </property>
</bean>
<mvc:annotation-driven conversion-service="conversionService"/>

但是也不起作用啊,就是不知道到底出了什么问题!!!!!!!!!!!

第三种方式:在对应的controller里面添加如下代码

@InitBinder
protected void initBinder(WebDataBinder binder) {
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  dateFormat.setLenient(false);
  binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}

很神奇,起作用了,但是这种方式比较麻烦,需要在每个需要处理的controller里面添加以上代码

希望以后能找到前面两种不能生效的原因!!

posted @ 2019-12-26 09:50  云淡风轻小学生  阅读(258)  评论(0)    收藏  举报