SpringMVC自定义类型转换器(日期格式)模板
2023-02-18 16:35:56 时间
创建一个转换类
要继承一个Converter类,才能定义
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateConverter implements Converter<String, Date> {
@Override
public Date convert(String s) {
try {
return new SimpleDateFormat("yyyy-MM-dd").parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
配置到spring-mvc.xml中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 扫描包-->
<context:component-scan base-package="com.itheima.controller"/>
<!-- 声明是为了对springmvc的组件做增强-->
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/>
<!-- 配置自定义的类型转换器-->
<bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.itheima.converter.StringToDateConverter"/>
</set>
</property>
</bean>
</beans>
注解方式
只需在要再要转换的类型上加上一个 @DateTimeFormat(pattern = “yyyy-MM-dd”) 如下:
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date ser;
相关文章
- 「Docker学习系列教程」9-Docker容器数据卷介绍
- 安全运维 | tcprepaly工具的安装与使用!
- 10个 解放双手的 IDEA 插件,少些冤枉代码
- 安全运维 | iptable使用详解
- 「JDK」解析 String str=““与 new String()
- 论文/代码速递2022.12.9!
- 新书《Pytorch深度学习之目标检测》!干货预览
- CVPR2022论文速递2022.7.4!最新成果demo展示
- ECCV&CVPR论文速递2022.7.5!最新成果demo展示
- ECCV2022 &CVPR2022论文速递2022.7.6!
- ECCV2022 &CVPR2022论文速递2022.7.7!
- ECCV2022 &CVPR2022论文速递2022.7.8!
- ECCV2022 &CVPR2022论文速递2022.7.11!
- ECCV2022 &CVPR2022论文速递2022.7.12!
- 阿里巴巴资深架构师深度解析微服务架构设计之SpringCloud+Dubbo
- ECCV2022 &CVPR2022论文速递2022.7.13!
- ECCV2022 &CVPR2022论文速递2022.7.14!
- 如何系统得对目标检测模型的误差分析?
- ECCV2022 &CVPR2022论文速递2022.7.15!
- ECCV2022 &CVPR2022论文速递2022.7.18!