Spring-MVC填坑之旅-返回json数据

时间:2021-08-30 07:26:47

本文是自己开发中所遇到的问题,对一些及百度到的解决方案做一个记录。

DispatcherServlet配置文件

    <!-- 定义跳转的文件的前后缀 ,视图模式配置-->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

每次返回数据都被拦截返回成jsp文件,在控制器的方法上添加@ResponseBody注解解决返回页面问题;

页面接收json数据报错:

The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.

解析类型不正确(自己理解)

配置注解及添加jar包解决:

<!-- 启用spring mvc 注解 -->
<context:annotation-config />
<mvc:annotation-driven >
<mvc:message-converters register-defaults="true">
<!-- Accept-Charset 大量打出问题 -->
<!-- <bean class="com.panku.common.converter.UTF8StringHttpMessageConverter">
<property name="writeAcceptCharset" value="false"></property>
</bean> -->
<!-- 将StringHttpMessageConverter的默认编码设为UTF-8 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" />
<property name="writeAcceptCharset" value="false"></property>
</bean>
<!-- 将Jackson2HttpMessageConverter的默认格式化输出为false -->
<!-- <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list><value>application/json;charset=UTF-8</value></list>
</property>
<property name="prettyPrint" value="false"/>
<property name="objectMapper">
<bean class="com.panku.common.utils.JsonMapper"></bean>
</property>
</bean> -->
<!-- 支持国产使用fastjson进行转换json字符串 -->
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>
<property name="features">
<array>
<value>WriteMapNullValue</value>
<value>WriteNullStringAsEmpty</value>
</array>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven> <!-- 提供无刷新返回json -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<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>application/json;charset=UTF-8</value></list>
</property>
<property name="prettyPrint" value="false"/>
</bean>

jar包:

jackson-annotations-2.7.0.jar,jackson-core-2.7.0.jar,jackson-databind-2.5.5.jar。