springmvc 解决@ResponseBody注解返回中文乱码

使用messageConverters

<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> 

在springmvc的配置文件中,将消息转换器的bean放在 <mvc:annotation-driven/> 的前面(上面),否则配置不会生效

 

需要jackson的依赖

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.8</version>
        </dependency>

如果上面这个不够,那就再追加或者替换为:

<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>  

 

posted @ 2018-09-11 11:08  由良大小姐  阅读(665)  评论(0编辑  收藏  举报