SpringMVC中文亂碼踩坑

CloverYou發表於2021-08-01

問題

使用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
}

相關文章