方式一:
在实体类的日期属性上直接添加@DateTimeFormart(pattern=’yyyy-MM-dd’)
方式二:
第一步:编写自定义日期转换类
该类实现接口converter,重写convert方法。
package cn.oyl.conversion;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
/**
* 自定义日期转换类
* @author Administrator
*
*/
public class StringToDate implements Converter<String, Date>{
//日期格式
private String format;
public StringToDate(){
}
//提供构造方法注入日期格式
public StringToDate(String format){
this.format=format;
}
//重写convert方法进行字符串对日期类型的转换
@Override
public Date convert(String str) {
Date date=null;
try {
date=new SimpleDateFormat(format).parse(str);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
}
**第二步:在springmvc的配置文件中显示的定义一个ConversionService(该类就是我们编写的自定义的日期转换类),并覆盖默认的ConversionService**
<!-- 声明自动映射mapping和处理方法-->
<mvc:annotation-driven conversion-service="myConversionService">
</mvc:annotation-driven>
<!--定义一个日期转换类 -->
<bean id="myConversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="cn.oyl.conversion.StringToDate">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd"/>
</bean>
</list>
</property>
</bean>
**第三步:测试运行**
方式三:
第一步:创建一个类,声明的方法使用@InitBinder注解
标注了@initBinder注解的方法会在控制器初始化时调用
在initBinder方法体内通过registerCustomEditor()方法注册一个自定义编辑器
第一个参数表示编辑器类型为日期类型,第二个参数表示使用自定义编辑器CoustomDateEditor,格式为yyyy-MM-dd,第三个参数表示该参数允许为空
package cn.oyl.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
public class BaseController {
@InitBinder
public void initBinder(WebDataBinder databinder){
databinder.registerCustomEditor(Date.class,
new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
}
}
需要用到日期类型参数的controller继承该类即可实现日期参数的转换