SpringMVC中文亂碼踩坑記錄

問題

使用SpringMVC在返回一個字符串時發生瞭中文亂碼問題。produces屬性無效

@RequestMapping(value = "/nihao", produces = "text/plain;charset=UTF-8")
@ResponseBody
public String hello(HttpServletResponse response) throws UnsupportedEncodingException {
    User user = new User();
    user.setSex("男");
    user.setName("Clover");
    user.setAge(19);
    return user.toString();
}
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: text/plain;charset=ISO-8859-1
Content-Length: 36
Date: Sun, 01 Aug 2021 12:20:21 GMT
Connection: close

{
  "name": "Clover",
  "sex": "?",
  "age": 19
}

添加常用的過濾器org.springframework.web.filter.CharacterEncodingFilter依然無法解決

<filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

問題根源

最後查看源碼時發現問題出現在處理內容協商的時候,SpringMVC使用瞭一個叫做org.springframework.http.converter.StringHttpMessageConverter的轉換器進行處理java.lang.String。在這個處理器中,有個一默認的編碼格式,它甚至使用瞭final修飾…..

public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");

並且,通過Postman或者REST Client發送請求時,Accept默認是*/*

解決方案

方案一

註冊一個StringHttpMessageConverter,註冊之後不再使用SpringMVC默認的。它可以將produces設置為Content-Type。也就是說@RequestMappingproduces屬性生效瞭

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
    </mvc:message-converters>
</mvc:annotation-driven>
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Accept-Charset: ...
Content-Type: text/plain;charset=utf-8
Content-Length: 37
Date: Sun, 01 Aug 2021 13:09:35 GMT
Connection: close

{
  "name": "Clover",
  "sex": "男",
  "age": 19
}

方案二

Accept問題,SpringMVC的默認StringHttpMessageConverter處理的是*/*,那手動設置一個Accept盡可能避開它…..

POST {{url}}/nihao HTTP/1.1
Accept: text/plain;charset=utf-8
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: text/plain;charset=utf-8
Content-Length: 38
Date: Sun, 01 Aug 2021 13:20:16 GMT
Connection: close

{
  "name": "Clover",
  "sex": "男",
  "age": 19
}

到此這篇關於SpringMVC中文亂碼踩坑記錄的文章就介紹到這瞭,更多相關SpringMVC中文亂碼內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: