spring mvc: view resolvers

调用过程

org.springframework.web.servler.ViewResolver 用来决定应该用哪个org.springframework.web.servlet.View的实例来创建并发送给客户端的response。

Dispatcherservlet 收到一个由request handler (通常为Controller中处理用户请求的方法)处理完用户请求而返回的值之后,在DispatcherServlet#doDispatch中调用了processDispatchResult


/**

* Handle the result of handler selection and handler invocation, which is

* either a ModelAndView or an Exception to be resolved to a ModelAndView.

*/

private void processDispatchResult(HttpServletRequest request, HttpServletResponse response,
    HandlerExecutionChain mappedHandler, ModelAndView mv, Exception exception) throws Exception

之后的call hierarchy如下:

DispatcherServlet call hierarchy.png

DispatcherServlet#resolveViewName中,遍历当前的所有ViewResolver,调用其resolveViewName方法:

protected View resolveViewName(String viewName, Map model, Locale locale,
            HttpServletRequest request) throws Exception {

        for (ViewResolver viewResolver : this.viewResolvers) {
            View view = viewResolver.resolveViewName(viewName, locale);
            if (view != null) {
                return view;
            }
        }
        return null;
    }

因此,ViewResolver#resolveViewName的语义就是:对于给定的viewName(由Controller返回),若是能够处理,则返回对应的View的实例,否则返回null,由下一个ViewResolver 处理。

找到合适的view之后,即调用其render方法,将从request handler 返回的数据(在spring mvc中称为model),进行数据绑定并对客户端进行相应:

//DispatcherServlet#render(...):
    view.render(mv.getModelInternal(), request, response);

详情可参考:SpringMVC#mvc-viewresolver

注册ViewResolver

从上面的代码可以看到,所有的ViewResolver保存在DispatcherServlet#viewResolvers中,而viewResolvers这个列表的值从context里面、与获取其他bean一样、来获取:

private void initViewResolvers(ApplicationContext context) {
        this.viewResolvers = null;

        if (this.detectAllViewResolvers) {
            // Find all ViewResolvers in the ApplicationContext, including ancestor contexts.
            Map matchingBeans =
                                        //从context中获取类型为ViewResolver的bean
                    BeanFactoryUtils.beansOfTypeIncludingAncestors(context, ViewResolver.class, true, false);
            if (!matchingBeans.isEmpty()) {
                this.viewResolvers = new ArrayList(matchingBeans.values());
                // We keep ViewResolvers in sorted order.
                OrderComparator.sort(this.viewResolvers);
            }
        }
        else {
            try {
                                //从context中获取类型为ViewResolver的bean
                ViewResolver vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class);
                this.viewResolvers = Collections.singletonList(vr);
            }
            catch (NoSuchBeanDefinitionException ex) {
                // Ignore, we'll add a default ViewResolver later.
            }
        }

        // Ensure we have at least one ViewResolver, by registering
        // a default ViewResolver if no other resolvers are found.
        if (this.viewResolvers == null) {
            this.viewResolvers = getDefaultStrategies(context, ViewResolver.class);
            if (logger.isDebugEnabled()) {
                logger.debug("No ViewResolvers found in servlet '" + getServletName() + "': using default");
            }
        }
    }

这里可以看到,ViewResolver是有顺序的(可以通过@order 来控制bean的顺序),若是多个ViewResolver可以处理同样的viewName,那么排在后面的ViewResolver将不起作用。

View#render

View#render 方法负责输出最终的HTTP response.
其接收三个参数:

  • Map model: 从Controller那边获得的跟业务相关的数据
  • HttpServletRequest request: �当前的HTTP request
  • HttpServletResponse response:当前正在构建的HTTP response,可将内容写入并发送给客户端

SpringMVC 提供了许多默认的View的实现类,可以满足大部分开发的需求——�如果完全使用spring框架的话。如果你打算自己控制render过程,有自己的一套模板机制,那么就可以创建自定义View的实现类了。

总结

这里简单讲述了当一个request被处理完成之后,将处理结果转化为response的过程中涉及到的类。大致流程如下:

  1. 接收到客户端的request,根据request查找对应的request handler(一般为Controller中的方法)
  2. request handler处理完之后返回,spring将处理结果包装为ModelAndView(将在其他文章中介绍这个过程)
  3. DispatcherServlet 根据ModelAndView的view name来选择对应的View:遍历ViewResolver,ViewResolver根据view name来返回对应的View的实现类(或返回null并交给下一个ViewResolver)
  4. 调用View#render来生成最终的response,在View的实现类中实现最终渲染并输出到response的过程。

你可能感兴趣的:(spring mvc: view resolvers)