自定义Converters
文章目录
11.1 什么是Converters
Contervers中文就是转化器的意思,在我们的SprinMVC中其实就是帮助我们转化数据的转化器,比如将String转化为int类型等等,在SpringMVC中为我们提供了大量的转换器。
- 在SpringMVC中还提供了一种转化器:
Formatter
,使用它也是可以对数据进行转化的
Converters和Formatter的区别:
转化器 | 说明 |
---|---|
Converters | 可以将任意的类型转化为其他任意的类型,可以用于很多层 |
Formatter | 可以将String类型转化为其他任意的类型,适用于web层 |
11.2 编写日期转化器
步骤:
- 实现Converter<S,T>接口,其中泛型S代表我们转化数据的类型,T代表我们需要转化成的数据类型
- 重写convert(S source)方法
// 实现接口,我们将String类型转化为日期类型
public class MyDateConverter implements Converter<String, Date> {
/**
* 转化时间控制器
* @param source 传入String时间
* @return Date类的时间
*/
@Override
public Date convert(String source) {
// 实例格式工厂
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
try {
// 返回解析对的对应的时间
return format.parse(source);
} catch (ParseException e) {
e.printstacktrace();
}
return null;
}
}
11.3 XML配置转化器
上面的一个转化器写好以后我们需要将该转化器配置到我们的SpringMVC框架中,首先我们可以使用XML配置文件来进行配置
注意:
- 我们这里需要重新定义一个转化器服务,模版SpringMVC已经提供好了,我们直接使用该类就可以
FormattingConversionServicefactorybean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.moon.controller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
<!--在mvc的注解驱动启动这里指定转化器服务为我们自定义的服务-->
<mvc:annotation-driven conversion-service="myConverteRSService"/>
<!--自定义一个转化器服务-->
<bean id="myConverteRSService" class="org.springframework.format.support.FormattingConversionServicefactorybean">
<!--添加转化器属性中添加我们自定义的转化器-->
<property name="converters">
<!--通过set集合把我们的自定义转化器注入-->
<set>
<bean class="com.moon.converter.MyDateConverter"/>
</set>
</property>
</bean>
......
</beans>
11.4 java类配置转化器
@Configuration
@EnableWebMvc
@ComponentScan("com.moon.controller")
public class MvcConfig implements WebMvcConfigurer {
......
/**
* 添加自定义的Converter
*
* @param registry 注册信息
*/
@Override
public void addFormatters(FormatterRegistry registry) {
// 添加自己写的Converter
registry.addConverter(new MyDateConverter());
}
......
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。