天天看點

SpringMVC 使用@ResponseBody傳回json 中文亂碼

這确實是個蛋疼的問題,Spring中解析字元串的轉換器預設編碼居然是ISO-8859-1

SpringMVC 使用@ResponseBody傳回json 中文亂碼

我現在用的Spring4.2.5,上面說的幾個方法都試了,最後發現隻有這兩個可以

方法一,使用(produces = "application/json; charset=utf-8")(如何整個項目都是以json格式的資料來互動的不建議使用,因為每一個都需要加編碼格式比較麻煩):

@RequestMapping(value="/getUsersByPage",produces = "application/json; charset=utf-8")
//    @RequestMapping("/getUsersByPage")
    @ResponseBody
    public String getUsersByPage(String page,String rows,String text,HttpServletRequest request,HttpServletResponse response){
           

方法二,在spring-mvc.xml中添加:

<!-- 處理請求傳回json字元串的中文亂碼問題 -->
    <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>