Sam*_*amo 8 java model-view-controller content-type ruby-on-rails spring-mvc
Rails控制器使得支持多种内容类型变得非常容易.
respond_to do |format|
format.js { render :json => @obj }
format.xml
format.html
end
Run Code Online (Sandbox Code Playgroud)
美丽.在一个控制器动作中,我可以轻松地响应多种内容类型,并且具有足够的灵活性,可以呈现我想呈现的内容,无论是模板,对象的序列化形式等.
我可以在Spring-MVC中做类似的事情吗?在Spring中支持多种内容类型的标准是什么?我见过涉及视图解析器的解决方案,但这看起来很难管理,特别是如果我想支持除xhtml和xml之外的JSON.
任何建议都表示赞赏,但更简单,更优雅的解决方案将更受欢迎;)
编辑
如果我断言查看解析器很难管理,请随时纠正我并提供一个示例.最好是可以返回xml,xhtml和JSON的.
在Spring 3中,你想要使用org.springframework.web.servlet.view.ContentNegotiatingViewResolver.
它需要一个媒体类型和列表ViewResolvers.从Spring文档:
<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"/>
Run Code Online (Sandbox Code Playgroud)
控制者:
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";
}
}
Run Code Online (Sandbox Code Playgroud)
您还需要包含Jackson JSON罐子.
| 归档时间: |
|
| 查看次数: |
6919 次 |
| 最近记录: |