springmvc日期的编写转换器
时间: 2023-07-12 20:08:47 浏览: 97
在SpringMVC中,日期的转换可以使用自定义的转换器来实现。具体步骤如下:
1. 创建一个实现了`Converter<String, Date>`接口的转换器类,用于将字符串类型的日期转换为Date类型的日期。
```java
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
return dateFormat.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
```
2. 在SpringMVC的配置文件中注册该转换器。
```xml
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.example.DateConverter"/>
</set>
</property>
</bean>
```
3. 在Controller中使用@DateTimeFormat注解指定日期类型的格式。
```java
@RequestMapping("/test")
public String test(@RequestParam("date") @DateTimeFormat(pattern="yyyy-MM-dd") Date date) {
// ...
}
```
这样就可以通过请求参数传递字符串类型的日期,然后使用转换器将其转换为Date类型的日期,最后在Controller中使用@DateTimeFormat注解指定日期类型的格式即可。
阅读全文
相关推荐


















