1. 程式人生 > >解決Spring MVC @ResponseBody返回中文字串亂碼問題

解決Spring MVC @ResponseBody返回中文字串亂碼問題

引起亂碼原因為spring mvc使用的預設處理字串編碼為ISO-8859-1,

具體參考org.springframework.http.converter.StringHttpMessageConverter類中public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");

解決方法:

第一種方法:

對於需要返回字串的方法添加註解,如下:

@RequestMapping(value="/loginSubmit.html", produces = "application/json; charset=utf-8")
@ResponseBody
public Object toLoginSubmit(HttpServletRequest request,HttpServletResponse response){
    return "登入成功中文顯示";
}

此方法只針對單個呼叫方法起作用。

第二種方法:

在配置檔案中加入

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes" value = "text/html;charset=UTF-8" />
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>