Solve the SpringMVC garbled problem

  • Problem scenario: using traditional JSP but using front-end and back-end separation, using JSON to transmit data,
    • The JSP settings are all correct:<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8"%>
    • The encoding filter configuration in web.xml didn't help.

Refer to the blog Spring MVC response message garbled
Refer to blog to solve the problem of Spring MVC @ResponseBody returning Chinese string garbled

Finally found a suitable method, and adjusted the configuration, more suitable for JSON

 <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                    <!-- 如果是前后端使用JSON作为主要数据交换格式就把JSON列为第一个, 否则就会被认为是Text -->
                        <value>application/json; charset=UTF-8</value>
                        <value>text/plain; charset=UTF-8</value>
                        <value>text/html; charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
  • And the above configuration also solves a JSON problem returned by Ajax that has been bothering me for JS operations:

    • The way to directly refer to the attribute or a['b'],
      • Iterating over collections: comes with a foreach loopdata.forEach(function(value){})
    • But sometimes it can't be used, it will be undefined, and eval('('+data+')') can be used after parsing
      • The reason is that Content-Type:application/json;charset=UTF-8if is text/plain, you need to use eval('('+data+')') to use
      • If it is set to JSON, it can be directly referenced and looped
  • A blog mentioned that viewing the response header information of Ajax requests made me realize, so by adjusting the above configuration, the request is set to return JSON format data first by default, which is just suitable for this application scenario

Guess you like

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