关于spring mvc 时间转换

来源:互联网 发布:ecmall多用户商城源码 编辑:程序博客网 时间:2024/05/22 16:38

新建项目遇到,controller 层接受 Date类型的参数时,无法把和struts2提供的方法一样把 string类型自动转化为date类型。

两种解决方法

方法一:

在相应的controller层上添加如下代码

/*@InitBinder  public void initBinder(WebDataBinder binder) {  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  format.setLenient(false);  binder.registerCustomEditor(Date.class, new CustomDateEditor(format , true));   //true:允许输入空值,false:不能为空值  }

这个只是在单独的controller层起作用。

方法二:

配置一个全局的方法实现转化。

java转化class

package cn.hkrt.base.util;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import org.springframework.core.convert.converter.Converter;public class DateFormatter implements Converter<String, Date> {    @Override    public Date convert(String source) {          SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");          try {               return simpleDateFormat.parse(source);          } catch (ParseException e) {               e.printStackTrace();          }          return null;    }}
在spring-mvc.xml中配置的内容
<mvc:annotation-driven conversion-service="conversionService"/><!-- 时间格式转化--><bean id="conversionService"class="org.springframework.format.support.FormattingConversionServiceFactoryBean"><property name="converters"><set><bean class="cn.hkrt.base.util.DateFormatter"></bean></set></property></bean>

说明:原先mvc注解注入,
<mvc:annotation-driven/>  使用这种方法需要把这注入修改一下。

方法三:

@DateTimeFormat(pattern = "yyyy-MM-dd")  private Date createTime;  
可以在相应的实体bean中添加注解进行转化。