解決SpringMVC返回字符串亂碼問題

現象:SpringMVC返回的結果中文亂碼,返回的編碼是ISO-8859-1

在這裏插入圖片描述

原因:spring MVC有一系列HttpMessageConverter去處理@ResponseBody註解的返回值,如返回list或其它則使用 MappingJacksonHttpMessageConverter,如果是string,則使用 StringHttpMessageConverter,而StringHttpMessageConverter使用的是字符集默認是ISO-8859-1,而且是final的。所以在當返回json中有中文時會出現亂碼。源碼如下

 * @author Arjen Poutsma
 * @author Juergen Hoeller
 * @since 3.0
 */
public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> {

	/**
	 * The default charset used by the converter.
	 */
	public static final Charset DEFAULT_CHARSET = StandardCharsets.ISO_8859_1;

解決方法一:單個請求的@ResponseBody後面加上produces=“text/html;charset=UTF-8;”(此方法只針對單個調用方法起作用),如下

    @GetMapping(value = "/hello", produces="text/html;charset=UTF-8;")
    public String hello() {
        return "hello, world測試";
    }

中文顯示正常了,可以看到返回的編碼爲UTF-8了
在這裏插入圖片描述

解決方法二:在配置文件中的<mvc:annotation-driven>中添加以下代碼

<mvc:annotation-driven>
    <mvc:message-converters>
    	<!-- 解決@ResponseBody返回中文亂碼 -->
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>text/html;charset=UTF-8</value>
                    <value>application/json;charset=UTF-8</value>
                    <value>*/*;charset=UTF-8</value>
                </list>
            </property>
            <!-- 用於避免響應頭過大 -->  
			<property name="writeAcceptCharset" value="false" /> 
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

中文顯示正常了,可以看到返回的編碼爲UTF-8了
在這裏插入圖片描述

解決方法二:在配置文件中的<mvc:annotation-driven>中使用MappingJackson2HttpMessageConverter轉換字符串,如下

<mvc:annotation-driven>
    <!-- 返回json數據,@response使用 -->
    <mvc:message-converters register-defaults="true">
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
            <property name="supportedMediaTypes">
                <list>
                    <value>text/html;charset=UTF-8</value>
                    <value>application/json;charset=UTF-8</value>
                </list>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

這種方式返回的字符串會有雙引號,如下
在這裏插入圖片描述

發佈了115 篇原創文章 · 獲贊 36 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章