1.在使用注解@DateTimeFormat(pattern)来将字符串格式化成Date时,需要引入处理日期格式化的bean对象,在spring的核心配置文件中配置:
配置头文件:(idea自动生成可能会生成cache的头文件,删除重新引用正确头文件即可)
xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
<!--可以在容器中实例化处理json,日志的格式化等功能-->
<mvc:annotation-driven></mvc:annotation-driven>
2.当对象内有一个Date类型的属性时:要在该属性上加@DateTimeFormat(pattern="yyyy-MM-dd)
后续跟其他基本类型属性操作类似,封装到对象中,传递即可
@Data
public class Emp {
private String name;
private Integer age;
private Dept dept;
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date jobDate;
}
<table>
<tr>
<td>姓名${emp.name}</td>
<td>年龄${emp.age}</td>
<td>部门编号${emp.dept.id}</td>
<td>入职日期${emp.jobDate}</td>
</tr>
</table>
二.对某一个controller中的日期做统一处理
1.添加依赖:joda-time
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.14</version>
</dependency>
2.在xxxController中绑定一个日期处理的handler:
@InitBinder
public void init(WebDataBinder webDataBinder){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(true);
webDataBinder.registerCustomEditor(Date.class,new CustomDateEditor(sdf,true));
}
此时将@DateTimeFormat注解注释掉,Date类型也能正常转换了.
三.全局的日期处理:自定义类型转换器
Converter为springmvc提供的用于自动类型转换的接口;
只要是把String转换成Date类型数据,都会被这个自定义的类型转换器拦截处理;
package com.woniu.converts;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 自定义字符串转日期
* */
public class StringToDateConvert implements Converter<String, Date> {
@Override
public Date convert(String source) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = sdf.parse(source);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
在spring的核心配置文件中配置自定义类型转换器:
<!-- 配置自定义类型转换器-->
<bean id="stringToDateConvert" class="com.woniu.converts.StringToDateConvert"></bean>
<!-- 配置处理类型转换器-->
<bean id="conversionServiceFactory" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<ref bean="stringToDateConvert"></ref>
</set>
</property>
</bean>
<!-- 在mvc中配置conversion-service-->
<mvc:annotation-driven conversion-service="conversionServiceFactory"></mvc:annotation-driven>
@DateTimeFormat注解会覆盖全局类型转换

本文介绍了在Spring MVC中如何使用@DateTimeFormat注解格式化日期参数,包括对单个Controller的处理和全局日期处理策略。通过配置自定义类型转换器,实现日期的统一格式化,同时提到了在对象属性上使用注解的方式。

被折叠的 条评论
为什么被折叠?



