Spring多视图混合输出RestFul
2016-11-16 本文已影响202人
KwTGmu
从结构上来说Spring的 ContentNegotiatingViewResolver是可以很方便的解决这个问题的。
但是在我开发使用的Spring4.3.2版本上却无法同时支持json与htm后缀。
表现为访问网页时控制台报错
Could not find acceptable representation
现在网上搜索到的资料多半是如下代码
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="ignoreAcceptHeader" value="true" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
<entry key="htm" value="application/json" />
</map>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<property name="marshaller">
<bean class="org.springframework.oxm.xstream.XStreamMarshaller"/>
</property>
</bean>
</list>
</property>
</bean>
比如以下网页:
参考1衔山的博客
参考2springMVC4(15)RestFul多视图混合输出
或者如全注解式配置Spring 4 MVC ContentNegotiatingViewResolver example
查看Spring源码后发现ignoreAcceptHeader属性在ContentNegotiatingViewResolver类中并不存在
查阅Spring官方源码后得知此属性已经于4.0版本失效
根据其提供的线索搜索ContentNegotiationManager关键词
找到以下资料参考3得以解决此问题
参考3Content Negotiation using Spring MVC
现配置参数如下:
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager">
</mvc:annotation-driven>
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="defaultContentType" value="application/json" />
<property name="ignoreAcceptHeader" value="true" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
<entry key="htm" value="application/json" />
</map>
</property>
</bean>
记之。