SpringMVC 返回JSON数据的配置

时间:2022-03-08 08:51:05

  spring-mvc-config.xml(文件名称请视具体情况而定)配置文件:

<!-- 启动Springmvc注解驱动 -->
<mvc:annotation-driven>
<!-- 返回json 方法一 需要导入 fastjson.jar包 -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false">
<!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<!-- 这里顺序不能反,一定先写text/html,不然ie下出现下载提示 -->
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven> <!-- 返回json 方法二 需要导入 jackson-annotations.jar,jackson-core.jar,jackson-databind.jar-->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html; charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html; charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean> --> <!-- 下面配置与返回json 无关 --> <!-- 自动将控制器加载到bean -->
<context:component-scan base-package="org.controller"></context:component-scan>
<!-- 配置处理静态资源的请求 -->
<mvc:resources location="/resources/" mapping="*/res/**"/> <!-- 拦截器配置 -->
<mvc:interceptors>
<bean class="org.aop.LoginInteceptor" />
</mvc:interceptors> <!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/><!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 -->
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
</bean> <!-- 上传 需要使用到的配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1046666000"/>
</bean> <!--配置全局的异常-->
<!-- <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.guanlan.util.SportException">error</prop>
</props>
</property>
</bean> -->