Springmvc框架json数据传递处理,解决方案2

上一个案例中,我们使用的是在controller中进行配置,来转换json数据在传递过程中的乱码问题,但是,这样每个用到json数据的controller都需要进行相应的配置,这样显然是不好的,那么我们就会考虑有没有以重统一的配置,答案当然是有的。

修改springmvc-servlet.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
 4     xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
 5     xsi:schemaLocation="
 6         http://www.springframework.org/schema/beans
 7         http://www.springframework.org/schema/beans/spring-beans.xsd
 8         http://www.springframework.org/schema/context
 9         http://www.springframework.org/schema/context/spring-context.xsd
10         http://www.springframework.org/schema/mvc
11         http://www.springframework.org/schema/mvc/spring-mvc.xsd">
12 
13     <context:component-scan base-package="cn.smbms.controller" />
14     <mvc:annotation-driven>
15         <!-- 添加消息转换器  解决json数据传递过程中的乱码问题-->
16         <mvc:message-converters>
17             <bean class="org.springframework.http.converter.StringHttpMessageConverter">
18                 <!-- 设置相应的属性 -->
19                 <property name="supportedMediaTypes">
20                     <list>
21                         <value>application/json;charset=UTF-8</value>
22                     </list>
23                 </property>
24             </bean>
25         </mvc:message-converters>
26     </mvc:annotation-driven>
27 
28     <mvc:resources mapping="/statics/**" location="/statics/" />
29     <!-- 完成视图的对应 -->
30     <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
31     <bean
32         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
33         <property name="prefix" value="/WEB-INF/jsp/" />
34         <property name="suffix" value=".jsp" />
35     </bean>
36 
37     <!-- 全局异常处理 -->
38     <bean
39         class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
40         <property name="exceptionMappings">
41             <props>
42                 <prop key="java.lang.RuntimeException">error</prop>
43             </props>
44         </property>
45     </bean>
46 
47     <!--配置MultipartResolver,用于文件上传 -->
48     <bean id="multipartResolver"
49         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
50         <property name="maxUploadSize" value="5000000"></property>
51         <property name="defaultEncoding" value="UTF-8"></property>
52     </bean>
53 
54 </beans>

UserController.java

运行结果:(同样不会出现乱码问题)

 

原文地址:https://www.cnblogs.com/dongyaotou/p/12261740.html