springmvc uses @ResponseBody annotation to return Chinese garbled characters

When using @ResponseBody, a String is returned, which contains Chinese. There is no garbled characters when the background returns, but garbled characters appear when the value of the front jsp page is retrieved, and the Chinese are displayed in the form of ?.

 

Solution: 

Modify the following configuration in spring-mvc.xml

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

 

 

 

Add the above configuration to <mvc:annotation-driven > </mvc:annotation-driven >.

 

Reason: The default encoding for parsing text in StringHttpMessageConverter is iso-8859-1, and the source code is as follows:

 

public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> {

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


	private final Charset defaultCharset;

	private final List<Charset> availableCharsets;

	private boolean writeAcceptCharset = true;
.....
omit others

 

 

Modified configuration to set encoding to utf-8.

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326307083&siteId=291194637