This time I will bring you how to deal with Chinese garbled characters when sending ajax in springmvc. What are the things to pay attention to when sending ajax in springmvc and Chinese garbled characters? The following is a practical case, let’s take a look one time.
Use spingmvc to send a request through ajax in JS and return the data in json format. The Chinese format is correct when taken out from the database, but is it wrong when displayed on the page? ? , after some research, there are several solutions. I am using sping-web-3.2.2,jarMethod 1:
In @RequestMapping Add produces = "text/html;charset=UTF-8"@RequestMapping(value = "/configrole", method = RequestMethod.GET, produces = "text/html;charset=UTF-8") public @ResponseBody String configrole() { ...... }
Method 2:
Because it is set by default in StringHttpMessageConverterCharacter set is ISO-8859-1 So get the source code, modify it to UTF-8 and package it into spring-web-3.2.2.jar
public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); .......... }
Method 3:
Modify the parameters of org.springframework.http.MediaType'sconstruction method, and add configuration to applicationContext-mvc.xml
public MediaType(String type, String subtype, Charset charset) { super(type, subtype, charset); }
Xml code
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <bean class="org.springframework.http.MediaType"> <constructor-arg value="text" /> <constructor-arg value="plain" /> <constructor-arg value="UTF-8" /> </bean> </list> </property> </bean>
Method 4##org.springframework.http.converter.StringHttpMessageConverter class is A class that handles requests or corresponding
string, and the default character set is ISO-8859-1, so when there is Chinese in the returned json, garbled characters will appear. There is a List
Solution, just add the following code to the
configuration file: <mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
What are the ways for Ajax to request async? How to useDetailed explanation of the use of AJAX’s XMLHttpRequest objectThe above is the detailed content of How to deal with Chinese garbled characters when sending ajax in springmvc. For more information, please follow other related articles on the PHP Chinese website!