|
对于最新的稳定版本,请使用 Spring Framework 7.0.6! |
视图解析
Spring MVC 定义了 ViewResolver 和 View 接口,这些接口允许你在浏览器中渲染模型而不将你绑定到特定的视图技术。ViewResolver 提供了视图名称和实际视图之间的映射。View 解决了在将数据交给特定视图技术之前的数据准备问题。
以下表格提供了有关ViewResolver层次结构的更多详细信息:
| ViewResolver | 描述 |
|---|---|
|
|
|
对 |
|
|
|
Convenient subclass of |
|
Implementation of the |
|
实现 |
处理
您可以链接视图解析器,方法是声明多个解析器bean,并且如果必要,通过设置order属性来指定顺序。请记住,order属性越高,视图解析器在链中的位置越靠后。
The contract of a ViewResolver specifies that it can return null to indicate that the
view could not be found. However, in the case of JSPs and InternalResourceViewResolver,
the only way to figure out if a JSP exists is to perform a dispatch through
RequestDispatcher. Therefore, you must always configure an InternalResourceViewResolver
to be last in the overall order of view resolvers.
重定向
特殊前缀 redirect: 在视图名称中允许你执行重定向。UrlBasedViewResolver(及其子类)将其识别为需要重定向的指令。视图名称的其余部分是重定向URL。
最终效果与控制器返回 RedirectView 相同,但现在控制器本身可以使用逻辑视图名称进行操作。逻辑视图名称(如 redirect:/myapp/some/resource)相对于当前的 Servlet 上下文进行重定向,而名称如 redirect:https://myhost.com/some/arbitrary/path 则重定向到绝对 URL。
转发
您还可以使用一个特殊的forward:前缀用于视图名称,这些视图名称最终由UrlBasedViewResolver及其子类解析。这会创建一个InternalResourceView,它执行一个RequestDispatcher.forward()。
因此,这个前缀对于InternalResourceViewResolver和InternalResourceView(用于JSP)没有用处,但如果您使用另一种视图技术但仍希望强制资源转发到Servlet/JSP引擎处理,可能会有所帮助。请注意,您也可以链接多个视图解析器。
内容协商
ContentNegotiatingViewResolver
does not resolve views itself but rather delegates
to other view resolvers and selects the view that resembles the representation requested
by the client. The representation can be determined from the Accept header or from a
query parameter (for example, "/path?format=pdf")。
The ContentNegotiatingViewResolver 选择一个合适的 View 来处理请求,通过比较请求的媒体类型与每个 ViewResolvers 关联的 View 支持的媒体类型(也称为 Content-Type)。列表中的第一个具有兼容 Content-Type 的 View 将表示返回给客户端。如果 ViewResolver 链无法提供兼容的视图,则会咨询通过 DefaultViews 属性指定的视图列表。后一种选项适用于可以渲染当前资源适当表示形式的单例 Views,而无需考虑逻辑视图名称。Accept 标头可以包含通配符(例如 text/*),在这种情况下,View 其中 Content-Type 是 text/xml 是一个兼容的匹配项。