Java 如何对text/html或application/json使用ContentNegotiatingViewResolver?
我用SpringMVC创建了一个RESTful服务。有很多教程,效果很好。现在,应用程序在某些情况下应该使用application/json或RESTful进行响应,在其他情况下应该使用普通的viewsolver和text/html(.jsp)进行响应。Java 如何对text/html或application/json使用ContentNegotiatingViewResolver?,java,rest,spring-mvc,servlets,Java,Rest,Spring Mvc,Servlets,我用SpringMVC创建了一个RESTful服务。有很多教程,效果很好。现在,应用程序在某些情况下应该使用application/json或RESTful进行响应,在其他情况下应该使用普通的viewsolver和text/html(.jsp)进行响应。 我认为ContentNegotingViewResolver最适合这种情况(是吗?) 现在我的问题是:我应该使用哪个视图/servlet/*直接显示json(REST结果)?这是我的servlet.xml: <beans xmlns="h
我认为ContentNegotingViewResolver最适合这种情况(是吗?) 现在我的问题是:我应该使用哪个视图/servlet/*直接显示json(REST结果)?这是我的servlet.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.atrioom" />
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="html" value="text/html" />
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</list>
</property>
</bean>
<!-- bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property
name="suffix"> <value>.jsp</value> </property> </bean -->
对于现在的每个请求,servlet都会查找要显示的.jsp
文件。这适用于text/html
和application/json
。我希望它的行为方式是在调用text/html
时提供一个视图(jsp),在调用application/json
时提供一个直接的json输出。
当我做一个只休息的服务时,我有这个工作。不需要jsp文件,应用程序直接返回json格式的数据。我不知道如何告诉谈判方在json的情况下该怎么做。我需要一个特殊的REST解析器吗?谁能帮我照一下吗 亲切的问候,
Alex您需要在视图解析器属性中配置映射Jackson2HttpMessageConverter。
除了MessageConverter my servlet.xml看起来不错之外,还需要咨询API?谢谢你的回答,顺便说一句!