spring mvc @requestmapping 最佳实践
检查了官方参考,发现了一百万种方法。
我想我有两组用例。 1.返回自定义的http响应,基本上我负责填写状态代码,响应正文(XML或JSON或文本)。 2.返回模型和视图。视图通常是一个 jsp 页面,并用模型中的数据填充视图。
我的问题是哪一个是更好的方法?可以将它们混合在一起。在我的第一次使用集中,是否可以返回一个视图?也有可能以一种方法同时拥有两者。类似如果 A 返回自定义的 http 响应,如果 B 返回 ModelAndView。
谢谢!
Checked the official ref, found a million ways to do things.
I guess I have 2 set of use cases.
1. return customized http response, basically I am responsible for filling in status code, response body(either XML or JSON or text).
2. return Model and View. view is a jsp page typically and fill in the view with data from modle.
My question is which is a better way to go? it possible to mix them together. In my first use set, is it possible to return a View? also is it possible to have both on them in one method. something like if A return customized http response, if B return ModelAndView.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
任何请求处理方法的返回值(ie 标记有
@RequestMapping
注释)必须标识一个视图(将生成 HTTP 响应)或生成 HTTP 响应本身每个处理程序方法都是独立的;我的意思是,您可以从某些处理程序方法返回视图名称并在其他处理程序方法中生成 HTTP 响应。
15.3.2.3 支持的处理程序方法参数和返回类型 在 Spring 3x 参考文档中 http:// static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/
作为在处理程序方法中生成 HTTP 响应的一种选项,您可以设置一个或多个视图解析器;普通视图分辨率(jsp 页面、图块等等)和一个或多个“特殊”视图分辨率(XML、JSON、等)。视图,您可能想要创建自己的视图类来扩展
org.springframework.web.servlet.view.AbstractView
。The return value from any request handling method (i.e. on marked with the
@RequestMapping
annotation must either identify a view (that will generate the HTTP Response) or generate the HTTP Response itself.Each handler method stands alone; by that I mean, you can return a view name from some handler methods and generate the HTTP Response in other handler methods.
Check out 15.3.2.3 Supported handler method arguments and return types in the Spring 3x reference document at http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/
As an option to generating the HTTP Response in the handler method, you could setup multiple view resolvers; one or more for normal view resolution (jsp pages, tiles, etc.) and one or more for "special" view resolution (XML, JSON, etc.). For the "special" views, you may want to create your own view class that extends
org.springframework.web.servlet.view.AbstractView
.您可以使用
ContentNegotiatingViewResolver
完成与您所描述的类似的操作,它可以根据请求处理提供不同的内容,而无需更改您的@RequestMapping
注释,或者事实上你是控制器中的任何东西。有大量关于如何使用此方法的资源,包括 这个和这个
You can accomplish something similar to what you are describing using the
ContentNegotiatingViewResolver
, which can deal with serving different content based on a request, with no changes required to your@RequestMapping
annotations, or in fact anything in you're controllers.There are plenty of resources on how to use this method, including this and this