If you find garbled characters in the content returned by spring's @responsbody, you need to solve them in the following ways.
1. Ensure that spring character Encoding Filter is configured in Web.xml:
XML Code <!-- Servlet Encoding Start --> <filter> <filter-name>Set character encoding</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>set character encoding</filter-name> <url-pattern>/*</url-pattern> </ filter-mapping> <!-- Servlet Encoding End -->
2. If the return value type under the @responsebody annotation method is String, the <mvc:annotation-driven/> is configured in the spring configuration file before the result is returned to the user; Then spring defaults to invoke a call Stringhttpmessageconverter
Class for the output of the content. Why would there be garbled?
Workaround 1: View the source code of the Stringhttpmessageconverter, the default encoding in the Stringhttpmessageconverter class is iso-8859-1 encoding, the encoding is the Western European character set code, Obviously will not support Chinese. PS: It feels like a spring bug, obviously it should be UTF-8, I've reported this bug on the Spring official web site.
Java code public static final Charset Default_charset = Charset.forname ("iso-8859-1"); Private final Charset Defaultcharset; Private final list<charset> availablecharsets;
And as you can see from the code above, the 3 variables associated with a character are final, meaning that we cannot dynamically change the 3 values above through a set or a constructor injection.
Further analysis of the source can be seen, stringhttpmessageconverter inheritance and abstracthttpmessageconverter<string>, analysis of the abstract class, the relevant operation character encoding method can be overridden, So we can customize a class to inherit Stringhttpmessageconverter, and then rewrite the related method, the code is as follows:
Java code /** * */ package com.chuanliu.platform.activity.basic.converter; import java.io.ioexception; import java.nio.charset.charset; import java.util.Arrays; import java.util.list; import org.springframework.http.httpoutputmessage; import org.springframework.http.mediatype; import org.springframework.http.converter.stringhttpmessageconverter; import org.springframework.util.streamutils; /** * for handling Chinese garbled problems: spring bug - * * In StringHttpMessageConverter, the Default char set is iso-8859-1 (Western European character set) * * @author Josh wang (Sheng) * * @email josh_wang23@hotmail.com */ Public class utf8stringhttpmessageconverter extends StringHttpMessageConverter { private static final mediatype utf8 = new mediatype ("Text ", " plain ", Charset.forname ("UTF-8"));