Rails Controller 使得支持多种内容类型变得非常容易。
respond_to do |format|
format.js { render :json => @obj }
format.xml
format.html
end
美丽。在一个 Controller 操作中,我可以轻松地响应多种内容类型,并且在我希望呈现的内容方面具有足够的灵 active ,无论是模板、对象的序列化形式等。
我可以在 Spring-MVC 中做类似的事情吗? Spring支持多种内容类型的标准是什么?我见过涉及 View 解析器的解决方案,但这看起来很难管理,特别是如果除了 xhtml 和 xml 之外我还想支持 JSON。
任何建议都会受到赞赏,但更简单和更优雅的解决方案将受到更多的赞赏;)
编辑
如果我断言 View 解析器难以管理是不正确的,请随时纠正我并提供示例。最好是一个可以返回 xml、xhtml 和 JSON 的。
最佳答案
在 Spring 3 中,您想使用 org.springframework.web.servlet.view.ContentNegotiatingViewResolver
。
它需要一个媒体类型列表和 ViewResolvers
。来自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"/>
Controller :
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 jar。
关于java - 在 Spring-MVC Controller 中支持多种内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4403643/