【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
最近搭建环境时,想使用@ResponseBody注解返回JSONObject数据,但是提示Http 500错误:
上网查了一下,才发现,@ResponseBody不是拿来就能用的,还需要进行下配置,配置对应的conver。
找了好一会,终于搞定,但是感觉好多朋友的博文基本都是转载,一个错就导致了个个错,所以决定自己整理一份
下面先说Jackson的方式
-
添加jar包支持
我的项目是Maven项目,所以pom.xml文件中添加依赖如下:
<!-- Jackson依赖 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.7.3</version>
</dependency
-
配置SpringMVC的配置文件
这里要注意SpringMVC和Jackson的版本,有部分老版本会使用org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter和org.springframework.http.converter.json.MappingJackson2HttpMessageConverter的配置。
我这里使用的是4.2的SpringMVC和2.7的Jackson
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list >
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 注解驱动配置 -->
<mvc:annotation-driven />
-
接下来,就可以使用@ResponseBody进行一下测试了
接下来再说下使用FastJson的情况下怎么配置
-
添加jar包支持
<!-- FastJson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.8</version>
</dependency>
-
修改SpringMVC配置文件
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list >
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
-
OK,大功告成,测试一下,没问题就继续前进之路吧。
或者是下面这种形式
<!-- 注解驱动配置 -->
<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>
其实Jackson和Fastjson的配置大同小异,只是使用的不同的conver文件而已
来源:oschina
链接:https://my.oschina.net/u/2245754/blog/662572