支持Spring-MVC控制器中的多种内容类型 [英] Supporting multiple content types in a Spring-MVC controller
问题描述
Rails控制器可以很容易地支持多种内容类型。
A Rails controller makes it very easy to support multiple content types.
respond_to do |format|
format.js { render :json => @obj }
format.xml
format.html
end
美丽。在一个控制器动作中,我可以轻松地响应多种内容类型,并且具有足够的灵活性,可以呈现我想呈现的内容,无论是模板,对象的序列化形式等等。
Beautiful. In one controller action I can easily respond to multiple content types with plenty of flexibility as to what I wish to render, be it a template, a serialized form of my object, etc.
我可以在Spring-MVC中做类似的事情吗?在Spring中支持多种内容类型的标准是什么?我见过涉及视图解析器的解决方案,但这看起来很难管理,特别是如果我想支持除xhtml和xml之外的JSON。
Can I do something similar to this in Spring-MVC? What is the standard for supporting multiple content types in Spring? I've seen solutions involving view resolvers, but this looks difficult to manage, especially if I want to support JSON in addition to xhtml and xml.
任何建议都表示赞赏,但更简单,更优雅的解决方案将更受欢迎;)
Any suggestions are appreciated, but the simpler and more elegant solutions will be appreciated more ;)
编辑
如果我断言视图解析器难以管理,请随时纠正我并提供示例。最好能返回xml,xhtml和JSON。
If I'm incorrect in asserting that a view resolver is difficult to manage, please feel free to correct me and provide an example. Preferably one that can return xml, xhtml, and JSON.
推荐答案
在Spring 3中,你想要使用 org.springframework.web.servlet.view.ContentNegotiatingViewResolver
。
In Spring 3, you want to use the org.springframework.web.servlet.view.ContentNegotiatingViewResolver
.
它需要一个媒体类型列表和 ViewResolvers
。来自 Spring docs :
It takes a list of media type and ViewResolvers
. From the Spring docs:
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="atom" value="application/atom+xml"/>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</list>
</property>
</bean>
<bean id="content" class="com.springsource.samples.rest.SampleContentAtomView"/>
财务总监:
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class BlogsController {
@RequestMapping("/blogs")
public String index(ModelMap model) {
model.addAttribute("blog", new Blog("foobar"));
return "blogs/index";
}
}
您还需要加入Jackson JSON罐子。
You'll also need to include the Jackson JSON jars.
这篇关于支持Spring-MVC控制器中的多种内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!