sping mvc中添加@ResponseBody,返回中文字符串时出现乱码,且在applicationContext-web.xml中已经配置StringHttpMessageConverter
<span style="white-space:pre"> </span><!-- 避免返回中文时出现乱码 -->
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<span style="white-space:pre"> </span><bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<span style="white-space:pre"> </span><property name="messageConverters">
<span style="white-space:pre"> </span><list>
<span style="white-space:pre"> </span><ref bean="stringHttpMessageConverter"/>
<span style="white-space:pre"> </span><ref bean="mappingJackson2HttpMessageConverter"/>
<span style="white-space:pre"> </span><ref bean="marshallingHttpMessageConverter"/>
<span style="white-space:pre"> </span></list>
<span style="white-space:pre"> </span></property>
<span style="white-space:pre"> </span></bean>
但是出现乱码,原因是因为将<mvc:annotation-driven/>配置放在了RequestMappingHandlerAdapter配置的前边了,导致后边配置的StringHttpMessageConverter配置无效,解决办法,因为<mvc:annotation-driven/>默认也会加载RequestMappingHandlerAdapter,所以需要把<mvc:annotation-driver/>放置到RequestMappingHandlerAdapter配置的后边,中文乱码的问题解决。
注:spring MVC 3.1之后,@RequestMapping
methods called RequestMappingHandlerMapping
and RequestMappingHandlerAdapter
,Prior to Spring 3.1, type and method-level request mappings were examined in two separate stages — a controller was selected first by theDefaultAnnotationHandlerMapping
and the actual method to invoke was narrowed down second by the AnnotationMethodHandlerAdapter
.