解决SSM 后台返回数据,前台显示中文乱码的问题
2021-11-08 本文已影响0人
乘风破浪的姐姐
问题:在Maven项目的实际运用场景中,当前台发起请求后,需要从后台返回数据给前台,此时如果返回的数据中包含中文,就会出现在后台查询出来是正常的,但是在前端显示的是乱码。
解决方案有两种:
方法一,在controller文件中, @RequestMapping注解中使用(produces = "application/json; charset=utf-8")
修改前:
@RequestMapping("/update")
@ResponseBody
public String updateMember() {
String path = ReadJsonFile.class.getClassLoader().getResource("updatemember.json").getPath();
String param = ReadJsonFile.readJsonFile(path);
System.out.println(param);
String result = HttpUtil.post("https://xxx/member/update", param);
System.out.println(result);
return "更新会员信息成功~";
}
修改后:
@RequestMapping(value="/update",produces = "application/json; charset=utf-8")
@ResponseBody
public String updateMember() {
String path = ReadJsonFile.class.getClassLoader().getResource("updatemember.json").getPath();
String param = ReadJsonFile.readJsonFile(path);
System.out.println(param);
String result = HttpUtil.post("https://xxx/member/update", param);
System.out.println(result);
return "更新会员信息成功~";
方法二,在 web.xml,spring-mvc.xml 配置文件中配置字符集
web.xml文件中加入:
<!-- 配置前端控制器 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!-- 配置字符集编码过滤器 -->
<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>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
然后在springmvc.xml中加入:
<!--让所有的Controller能够解析,注意<mvc:annotation-driven>是用来解决@ResponseBody传输字符串中文乱码问题-->
<mvc:annotation-driven>
<mvc:message-converters>
<!-- @ResponseBody乱码问题,将StringHttpMessageConverter的默认编码设为UTF-8 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
保存后,重新启动项目,再次访问,原先的中文乱码均已经正常显示。