美文网首页
SpringMVC 返回中文字符串乱码

SpringMVC 返回中文字符串乱码

作者: Ethan_Walker | 来源:发表于2017-08-29 00:49 被阅读18次

引起乱码原因为springmvc使用的默认处理字符串编码为ISO-8859-1,
参考org.springframework.http.converter.StringHttpMessageConverter类中:

image.png

1. 在方法上添加注解

此方法只针对单个调用方法起作用。

@RequestMapping(value="/demo", produces = "application/json; charset=utf-8")  
@ResponseBody  
public Object toLoginSubmit(HttpServletRequest request,HttpServletResponse response){  
    return "中文显示";  
}  

2. 全局配置字符串乱码处理

springmvc.xml中配置


<!-- 处理请求时返回字符串的中文乱码问题 -->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

相关文章

网友评论

      本文标题:SpringMVC 返回中文字符串乱码

      本文链接:https://www.haomeiwen.com/subject/spmndxtx.html