MVC——17 SpringMVC 对 Date 类型转换

SpringMVC 对 Date 类型转换

1. 在 springmvc.xml 中配置

代码中不需要做任何修改

  1. 必须额外导入 joda-time.jar
  2. 时间类型 java.sql.Date
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotati on-driven>
<bean id="conversionService"class="org.springframework.format.support.Formattin gConversionServiceFactoryBean">
<property name="registerDefaultFormatters" value="false" /> <property name="formatters"> <set> 
<bean class="org.springframework.format.number.NumberForm atAnnotationFormatterFactory" /> </set> 
</property> 
<property name="formatterRegistrars"> <set> <bean class="org.springframework.format.datetime.joda.Jod aTimeFormatterRegistrar">
<property name="dateFormatter"> <bean class="org.springframework.format.datetime.joda.Dat eTimeFormatterFactoryBean"> 
<property name="pattern" value="yyyy-MM-dd" /> 
</bean> 
</property> 
</bean> 
</set> 
</property> 
</bean>

2.使用注解。在需要转换的参数或实体类属性上添加

@DateTimeFormatter(pattern=”表达式”)
  1. 使用 Date 参数接收
@RequestMapping("demo") 
public String demo(@DateTimeFormat(pattern="yyyy-MM-dd") Date time){ 
System.out.println(time); 
return "abc.jsp"; 
}
  1. 在实体类中
@RequestMapping("demo") 
public String demo( Demo1 demo){ 
System.out.println(demo); 
return "abc.jsp"; 
}
public class Demo1 { 
@DateTimeFormat(pattern="yyyy/MM/dd") 
private Date time;
}
  1. 注意地方
    ①不需要导入额外 jar
    ②Date 是 java.util.Date
发布了167 篇原创文章 · 获赞 15 · 访问量 6160

猜你喜欢

转载自blog.csdn.net/Re_view/article/details/100733932