今天分享一个知识,
最近在自学springmvc 遇到的一件特别恼人的事儿, 写好的demo 在请求网络数据时总是失败返回406错误,修改好了406错误,无缘无故有给我返回500, 网上找了很多资料也没能解决我的问题,就开始代码乱拼,结果你懂得,突然就能把对象返回成json数据给客户端了.小小高兴了n小时,然后静下心来好好的对比了一下代码,发现和以前的代码没有什么不同,唯一的只是在配置上出了点问题,
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:cache="http://www.springframework.org/schema/cache" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.8.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
<context:component-scan base-package="net.controller">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<mvc:annotation-driven /> (这段代码就是不同的地方)
<!--配置一个viewResolver来处理返回的页面,配置前置和后置 -->
<bean id="viewresolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
我专门搜了一下这段代码的功能,于是在这里 http://kingliu.iteye.com/blog/1972973
找到了一句话 " 当我们需要controller返回一个map的json对象时,可以设定<mvc:annotation-driven /> ",我专门的试了一下去掉了这句话,果然出现了406的错误.搞死我了,当然这可能只是出现406的一个可能的原因,我遇到了所以分享给大家,希望大家少走弯路.
附带我的demo地址: git@github.com:Marshallee/SpringMVC_JSON.git