Spring MVC解决@ResponseBody注解返回中文乱码

@RequestMapping的produces方法

第一种解决方案是使用@RequestMapping注解的produces方法。写法如下:

@RequestMapping(value = "/testResponseBody",produces = "application/json;charset=utf-8")

在方法上加上这个注解就可以了。但是这样写的话有限制,只能在特定的方法上面使用。如果需要全局都使用的话,需要修改SpringMVC的配置文件。

 

使用messageConverters

第二种解决办法是使用HttpMessageConverter接口的相关实现类。我们先看配置文件中的配置信息。

	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" >
		<property name="messageConverters">
			<list>
				<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
				<bean 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>
			</list>
		</property>
	</bean>

并且需要在Maven依赖中配置上Jackjson的依赖。

 

		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-asl</artifactId>
			<version>1.9.13</version>
		</dependency>

昨天让我郁闷的是,我这样配置了之后确依然是不生效。后来才发现是位置放的不对,需要把这段配置放到<mvc:annotation-driven />的上面。真是很无语的感觉!!!

注意:一定要放到<mvc:annotation-driven />的上面,否则不会生效。

使用<mvc:message-converters>

还有一种方式是在SpringMVC的配置文件中的<mvc:annotation-driven>中加入<mvc:message-converters>的配置。具体配置内容如下:

    <!-- SpringMVC注解驱动 -->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
            <bean 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>
        </mvc:message-converters>
    </mvc:annotation-driven>
注意:始用这种配置的时候,需要去掉RequestMappingHandlerMapping、RequestMappingHandlerAdapter或者DefaultAnnotationHandlerMapping、AnnotationMethodHandlerAdapter的Bean配置,要不然可能会不生效。

另外:对于请求映射处理类返回类型可以是String也可以是Object(如果Object是JavaBean的话,SpringMVC会用Jackson来转换成json字符串)

微信关注

WeChat

 

本站为非盈利性站点,所有资源、文章等仅供学习参考,并不贩卖软件且不存在任何商业目的及用途,如果您访问和下载某文件,表示您同意只将此文件用于参考、学习而非其他用途。
本站所发布的一切软件资源、文章内容、页面内容可能整理来自于互联网,在此郑重声明本站仅限用于学习和研究目的;并告知用户不得将上述内容用于商业或者非法用途,否则一切后果请用户自负。
如果本站相关内容有侵犯到您的合法权益,请仔细阅读本站公布的投诉指引页相关内容联系我,依法依规进行处理!
作者:理想
链接:https://www.imyjs.cn/archives/604
THE END
二维码
Spring MVC解决@ResponseBody注解返回中文乱码
@RequestMapping的produces方法 第一种解决方案是使……
<<上一篇
下一篇>>
文章目录
关闭
目 录