1、问题
在使用SpringMVC3时,需要对response到页面的数据进行编码设置则需要自定义注解数据格式化类来对页面传过来的字符串进行格式化。
编码设置:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" > <property name="messageConverters"> <list> <bean class = "org.springframework.http.converter.StringHttpMessageConverter"> <property name = "supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean>
Formatter设置:
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="formatters"> <list> <bean class="com.grgbanking.it.common.formatter.TimestampFormatAnnotationFormatterFactory"/> </list> </property> </bean> <mvc:annotation-driven conversion-service="conversionService"/>
当两者按上面的设置好后,StringHttpMessageConverter不起作用了。
2、原因
<mvc:annotation-driven />的配置如下:
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> <property name="order" value="1" /> </bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="webBindingInitializer"> <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"> <property name="conversionService" ref="conversionService" /> <property name="validator" ref="validator" /> </bean> </property> </bean> <bean id="conversionService" class="org.springframework.samples.petclinic.util.PetclinicConversionServiceFactory" /> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
从上面的配置信息来看,<mvc:annotation-driven />相当于注册了DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter两个bean。
所以我们在上面配置的AnnotationMethodHandlerAdapter在<mvc:annotation-driven />后是不起作用的。<mvc:annotation-driven
/>包括了一个默认的AnnotationMethodHandlerAdapter功能。
3、解决
把StringHttpMessageConverter配置在<mvc:annotation-driven
/>里面。
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="formatters"> <list> <bean class="com.grgbanking.it.common.formatter.TimestampFormatAnnotationFormatterFactory"/> </list> </property> </bean> <!-- 设置转换器 --> <mvc:annotation-driven conversion-service="conversionService"> <mvc:message-converters> <bean class = "org.springframework.http.converter.StringHttpMessageConverter"> <property name = "supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
注:上面方法只适用于SpringMVC
3.1.x以上版本。
时间: 2024-09-30 20:40:05