【发布时间】:2013-01-31 17:49:27
【问题描述】:
我们使用 Spring MVC 开发了一个标准的 Java Web 应用程序,并且最近尝试从 3.0.6 升级到 3.2.0。我们几乎所有的 servlet 响应都是 JSP 或 Json 视图,但也有一些是 pdf 请求,扩展名为“pdf”。
在春季 3.0.6 中 我们已经进行了这个设置,取自 Spring MVC 文档。
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="pdf" value="application/pdf"/>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
</map>
与 XMLViewResolver 结合使用效果很好。
更新到3.2.0后出现故障:
Error creating bean with name' org.springframework.web.servlet.view.ContentNegotiatingViewResolver#0' defined in class path resource [dispatcher-test-servlet.xml]: Invocation of init method failed; nested exception is
java.lang.ClassCastException: java.lang.String cannot be cast to org.springframework.http.MediaType'
在调查了文档和一些博客之后,这种配置似乎有效:
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="contentNegotiationManager">
<bean class="org.springframework.web.accept.ContentNegotiationManager">
<constructor-arg>
<list>
<!-- These are evaluated in order -->
<!-- Is there a media type based on suffix? -->
<bean class="org.springframework.web.accept.PathExtensionContentNegotiationStrategy">
<constructor-arg>
<map>
<entry key="html" value="text/html" />
<entry key="json" value="application/json" />
<entry key="pdf" value="application/pdf" />
</map>
</constructor-arg>
</bean>
<!-- Else use request header -->
<bean
class="org.springframework.web.accept.HeaderContentNegotiationStrategy">
</bean>
</list>
</constructor-arg>
</bean>
</property>
但是,我们已经尝试使用此配置运行新的 Spring MVC 测试框架,并再次获得 ClassCast 异常,因此测试框架似乎没有以与应用程序运行时相同的方式初始化 bean... 有没有人清楚地解释如何在 Spring 3,2 中以健壮的方式配置 ContentNegotiatingViewResolver? 谢谢
理查德
【问题讨论】:
-
谢谢 - 但在删除“价值”标签后,我在运行 MVC 测试时仍然遇到同样的问题。
标签: spring spring-mvc content-negotiation