局部配置:使用Spring的注解
在字段上添加注解: @DateTimeFormat(pattern=”yyyy-MM-dd”)
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birthday;//出生日期
全局配置
通过配置文件
自定类,实现Converter接口
public class StringToDateConverter implements Converter<String, Date> {
@Override
public Date convert(String str) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = sdf.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
配置到springMVC的装配中
<bean class="org.springframework.context.support.ConversionServiceFactoryBean"
id="conversionService">
<property name="converters">
<list>
<bean class="smbms.utils.StringToDateConverter"></bean>
</list>
</property>
</bean>
<!-- springMVC的自动装配 -->
<mvc:annotation-driven conversion-service="conversionService"/>
通过继承
i. 定义类,在方法的实现上加上注解@InitBinder
public class BaseController {
@InitBinder
public void initDateBinder(WebDataBinder dataBinder) {
dataBinder.registerCustomEditor(Date.class,
new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
}
}
需要进行日期格式转化的类,让其继承
public class UserController extends BaseController{
}