springmvc .html请求返回json数据转换错误

来源:互联网 发布:淘宝已评的五星在哪找 编辑:程序博客网 时间:2024/05/20 21:20

备忘。(感谢wangning帮助解决问题)

问题:

项目拦截.html请求 不同于常规的http://xxxx/a/b的请求方式,采用http://xxxx/a/b.html请求在返回对象转换成JSON时报错。


原因:

springmvc默认的数据转换管理器ContentNegotiationManagerFactoryBean默认配置 会根据请求路径来解析数据类型。比如a/b.html会当做html文件解析。a/b.json当做json数据解析。


解决办法:

修改默认配置指定数据转换管理器


具体配置如下:


1、web.xml中

<!-- spring mvc 配置 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>




2、spring-mvc.xml中


<!-- 指定数据转换管理器 -->

<mvc:annotation-driven content-negotiation-manager="cnManager"/>

<!--  favorPathExtension属性值默认为true 会根据请求路径来识别你的数据类型,入.html返回html。.json返回json-->
<bean id="cnManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">  
        <property name="favorPathExtension" value="false"/>  
        <property name="defaultContentType" value="text/html"/>  
        <property name="mediaTypes">  
            <map>  
                <entry key="xml" value="application/xml"/>  
                <entry key="json" value="application/json"/>
            </map>  
        </property>  
    </bean>



0 0
原创粉丝点击