首页 文章资讯内容详情

springMVC的 Converter转换器 和 Formatter

2026-06-01 2 花语

本文内容纲要:

-Converter转换器 -Formatter -选择Converter,还是Formatter

Converter转换器

spring的Converter是可以将一种类型转换成另一种类型的一个对象,自定义Converter需要实现Converter接口

日期转换器

importjava.text.ParseException; importjava.text.SimpleDateFormat; importjava.util.Date; importorg.springframework.core.convert.converter.Converter; /** *字符串日期格式转换器 * */ publicclassCustomGlobalStrToDataConverterimplementsConverter<String,Date>{ privateStringdatePattern;//日期格式 //创建对象,并传入构造参数 publicCustomGlobalStrToDataConverter(StringdatePattern){ this.datePattern=datePattern; } @Override publicDateconvert(Stringsource){ try{ Datedate=newSimpleDateFormat(datePattern).parse(source); returndate; }catch(ParseExceptione){ e.printStackTrace(); } returnnull; } }

使用SpringMVC自定义的Converter,需要在SpringMVC的配置文件中加入如下配置

<!--注解驱动:替我们显示的配置了最新版的注解的处理器映射器和处理器适配器--> <mvc:annotation-drivenconversion-service="myConversionService"/> <!--配置自定义转换器注意:一定要将自定义的转换器配置到注解驱动上,id不能使用conversionService,不然会出现ArrayList<?>的异常--> <beanid="myConversionService"class="org.springframework.context.support.ConversionServiceFactoryBean"> <propertyname="converters"> <set> <!--指定自定义转换器的全路径名称--> <beanclass="com.guorong.controller.converter.CustomGlobalStrToDataConverter"> <constructor-argname="datePattern"type="java.lang.String"value="yyyy-MM-ddhh:mm:ss"/> </bean> </set> </property> </bean>

Formatter

Formatter和Converter一样,是将一种类型转换成另一种类型,但是,Formatter的源类型必须是一个String,目标类型是java类型.

importjava.text.ParseException; importjava.text.SimpleDateFormat; importjava.util.Date; importjava.util.Locale; importorg.springframework.format.Formatter; publicclassDateFormatterimplementsFormatter<Date>{ privateStringdatePattern;//日期格式字符串 privateSimpleDateFormatdateFormat;//日期格式类 publicDateFormatter(StringdatePattern){ this.datePattern=datePattern; dateFormat=newSimpleDateFormat(datePattern); } //将Date格式化为指定日期字符串,返回目标对象的字符串表示法 @Override publicStringprint(Datedate,Localelocale){ returndateFormat.format(date); } //将字符串日期解析成Date对象 @Override publicDateparse(Stringsource,Localelocale)throwsParseException{ returndateFormat.parse(source); } }

springMVC配置文件

<!--注解驱动:替我们显示的配置了最新版的注解的处理器映射器和处理器适配器--> <mvc:annotation-drivenconversion-service="conversionService"/> <beanid="conversionService"class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <propertyname="formatters"> <set> <beanclass="com.guorong.controller.converter.DateFormatter"> <constructor-argname="datePattern"type="java.lang.String"value="yyyy-MM-dd"/> </bean> </set> </property> </bean>

选择Converter,还是Formatter

Converter是一般工具,可以将一种类型转换成另一种类型,例如,将String转换成Date,或者Long转换成Date,Conveter既可以用在web层,也可以用在其他层中,Formatter只能讲String转换层另一种java类型,例如,将String转换成Date,但它不可能将Long转换成Date类型,因此Formatter适用于web层,因此,SpringMVC应用程序中,选择Formatter比选择Converter更合适.

本文内容总结:Converter转换器,Formatter,选择Converter,还是Formatter,

原文链接:https://www.cnblogs.com/guo-rong/p/9198106.html