• SpringMVC DispatcherServlet-------视图渲染过程


    整个spring mvc的架构如下图所示:

    现在来讲解DispatcherServletDispatcherServlet的最后一步:视图渲染。视图渲染的过程是在获取到ModelAndView后的过程。

    视图渲染的过程:

    DispatcherServlet.java

    doService()--->doDispatch()--->processDispatchResult()--->render()

    processDispatchResult():主要处理异常、请求状态及触发请求完成事件,图的渲染工作交给了render().

    render()渲染过程如下:

    1. 判断ModelAndView中view是否为view name,没有获取其实例对象:如果是根据name,如果是则需要调用resolveViewName从视图解析器获取对应的视图(View)对象;否则ModelAndView中使用getview方法获取view对象。

    2. 然后调用view的render()方法。

    代码如下:

     1 /**
     2      * Render the given ModelAndView.
     3      * <p>This is the last stage in handling a request. It may involve resolving the view by name.
     4      * @param mv the ModelAndView to render
     5      * @param request current HTTP servlet request
     6      * @param response current HTTP servlet response
     7      * @throws ServletException if view is missing or cannot be resolved
     8      * @throws Exception if there's a problem rendering the view
     9      */
    10     protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {
    11         // Determine locale for request and apply it to the response.
    12         Locale locale = this.localeResolver.resolveLocale(request);
    13         response.setLocale(locale);
    14 
    15         View view;
    16         if (mv.isReference()) {
    17             // We need to resolve the view name.
    18             view = resolveViewName(mv.getViewName(), mv.getModelInternal(), locale, request);
    19             if (view == null) {
    20                 throw new ServletException("Could not resolve view with name '" + mv.getViewName() +
    21                         "' in servlet with name '" + getServletName() + "'");
    22             }
    23         }
    24         else {
    25             // No need to lookup: the ModelAndView object contains the actual View object.
    26             view = mv.getView();
    27             if (view == null) {
    28                 throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " +
    29                         "View object in servlet with name '" + getServletName() + "'");
    30             }
    31         }
    32 
    33         // Delegate to the View object for rendering.
    34         if (logger.isDebugEnabled()) {
    35             logger.debug("Rendering view [" + view + "] in DispatcherServlet with name '" + getServletName() + "'");
    36         }
    37         try {
    38             view.render(mv.getModelInternal(), request, response);
    39         }
    40         catch (Exception ex) {
    41             if (logger.isDebugEnabled()) {
    42                 logger.debug("Error rendering view [" + view + "] in DispatcherServlet with name '" +
    43                         getServletName() + "'", ex);
    44             }
    45             throw ex;
    46         }
    47     }

    那么view 是如何渲染的?我们来看看view的定义:

     1 org.springframework.web.servlet
     2 Interface View
     3 
     4 All Known Subinterfaces: 
     5 SmartView 
     6 All Known Implementing Classes: 
     7 AbstractAtomFeedView, AbstractExcelView, AbstractFeedView, AbstractJasperReportsSingleFormatView, AbstractJasperReportsView, AbstractJExcelView, AbstractPdfStamperView, AbstractPdfView, AbstractRssFeedView, AbstractTemplateView, AbstractUrlBasedView, AbstractView, ConfigurableJasperReportsView, FreeMarkerView, InternalResourceView, JasperReportsCsvView, JasperReportsHtmlView, JasperReportsMultiFormatView, JasperReportsPdfView, JasperReportsXlsView, JstlView, MappingJackson2JsonView, MappingJacksonJsonView, MarshallingView, RedirectView, TilesView, TilesView, VelocityLayoutView, VelocityToolboxView, VelocityView, XsltView 
     8 
     9 --------------------------------------------------------------------------------
    10 
    11 
    12 public interface ViewMVC View for a web interaction. Implementations are responsible for rendering content, and exposing the model. A single view exposes multiple model attributes. 
    13 This class and the MVC approach associated with it is discussed in Chapter 12 of Expert One-On-One J2EE Design and Development by Rod Johnson (Wrox, 2002). 
    14 
    15 View implementations may differ widely. An obvious implementation would be JSP-based. Other implementations might be XSLT-based, or use an HTML generation library. This interface is designed to avoid restricting the range of possible implementations. 
    16 
    17 Views should be beans. They are likely to be instantiated as beans by a ViewResolver. As this interface is stateless, view implementations should be thread-safe.

    spring提供了如此多的视图,那么肯定的是也会有很多视图解析器:

     1 org.springframework.web.servlet
     2 Interface ViewResolver
     3 
     4 All Known Implementing Classes: 
     5 AbstractCachingViewResolver, AbstractTemplateViewResolver, BeanNameViewResolver, ContentNegotiatingViewResolver, FreeMarkerViewResolver, InternalResourceViewResolver, JasperReportsViewResolver, ResourceBundleViewResolver, TilesViewResolver, TilesViewResolver, UrlBasedViewResolver, VelocityLayoutViewResolver, VelocityViewResolver, XmlViewResolver, XsltViewResolver 
     6 Functional Interface: 
     7 This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. 
     8 
     9 --------------------------------------------------------------------------------
    10 
    11 
    12 public interface ViewResolverInterface to be implemented by objects that can resolve views by name. 
    13 View state doesn't change during the running of the application, so implementations are free to cache views. 
    14 
    15 Implementations are encouraged to support internationalization, i.e. localized view resolution.

    其中,针对JSP提供的InternalResourceViewResolver与InternalResourceView。

    我们先看一下view的render方法是什么样子的?

    根据InternalResourceView的继承关系:


     最终找到render方法在AbstractView中,如下代码所示:

     1 /**
     2      * Prepares the view given the specified model, merging it with static
     3      * attributes and a RequestContext attribute, if necessary.
     4      * Delegates to renderMergedOutputModel for the actual rendering.
     5      * @see #renderMergedOutputModel
     6      */
     7     @Override
     8     public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
     9         if (logger.isTraceEnabled()) {
    10             logger.trace("Rendering view with name '" + this.beanName + "' with model " + model +
    11                 " and static attributes " + this.staticAttributes);
    12         }
    13 
    14         Map<String, Object> mergedModel = createMergedOutputModel(model, request, response);
    15         prepareResponse(request, response);
    16         renderMergedOutputModel(mergedModel, request, response);
    17     }

    流程如下:

    创建一个动态值和静态属性的map;

    设置response 报文头;

    把渲染view的工作放到renderMergedOutputModel()实现中,这个留给InternalResourceView来实现。

    我们看看这个实现:

     1 /**
     2      * Render the internal resource given the specified model.
     3      * This includes setting the model as request attributes.
     4      */
     5     @Override
     6     protected void renderMergedOutputModel(
     7             Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
     8 
     9         // Determine which request handle to expose to the RequestDispatcher.
    10         HttpServletRequest requestToExpose = getRequestToExpose(request);
    11 
    12         // Expose the model object as request attributes.
    13         exposeModelAsRequestAttributes(model, requestToExpose);
    14 
    15         // Expose helpers as request attributes, if any.
    16         exposeHelpers(requestToExpose);
    17 
    18         // Determine the path for the request dispatcher.
    19         String dispatcherPath = prepareForRendering(requestToExpose, response);
    20 
    21         // Obtain a RequestDispatcher for the target resource (typically a JSP).
    22         RequestDispatcher rd = getRequestDispatcher(requestToExpose, dispatcherPath);
    23         if (rd == null) {
    24             throw new ServletException("Could not get RequestDispatcher for [" + getUrl() +
    25                     "]: Check that the corresponding file exists within your web application archive!");
    26         }
    27 
    28         // If already included or response already committed, perform include, else forward.
    29         if (useInclude(requestToExpose, response)) {
    30             response.setContentType(getContentType());
    31             if (logger.isDebugEnabled()) {
    32                 logger.debug("Including resource [" + getUrl() + "] in InternalResourceView '" + getBeanName() + "'");
    33             }
    34             rd.include(requestToExpose, response);
    35         }
    36 
    37         else {
    38             // Note: The forwarded resource is supposed to determine the content type itself.
    39             if (logger.isDebugEnabled()) {
    40                 logger.debug("Forwarding to resource [" + getUrl() + "] in InternalResourceView '" + getBeanName() + "'");
    41             }
    42             rd.forward(requestToExpose, response);
    43         }
    44     }

    流程可以归纳为以下几步:

    1. 包装request,供RequestDispatcher来使用;

    2. 将map中的属性和值作为属性放入包装的request;

    3. 将不同实现类的helper放入包装的request中;

    4. 渲染前的准备,确定request dispatcher要跳向(或者inclue)的路径

    5. 获取request dispatcher。

    6. 根据request中是否包含include uri属性来确实是forward或者include方法。

    forward是跳向服务器的servlet, JSP文件, 或者 HTML文件。

     Includes the content of a resource (servlet, JSP page,HTML file) in the response.

    注意,在上述流程中出现了RequestDispatcher,那么这类的作用是什么呢?

    1 getRequestDispatcher
    2 
    3 RequestDispatcher getRequestDispatcher(java.lang.String path)
    4 Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. A RequestDispatcher object can be used to forward a request to the resource or to include the resource in a response. The resource can be dynamic or static.
    5 The pathname specified may be relative, although it cannot extend outside the current servlet context. If the path begins with a "/" it is interpreted as relative to the current context root. This method returns null if the servlet container cannot return a RequestDispatcher.
    6 
    7 The difference between this method and ServletContext#getRequestDispatcher is that this method can take a relative path.

    简洁的来说,

    1. RequestDispatcher 是一个包装器,它将制定路径的(静态或者动态)资源包装起来。RequestDispatcher 可以用于将一个请求分发给指定的资源或者包裹响应报文中的资源。

    2. RequestDispatcher 的获取,有这种形式,一种使用ServletRequest.getRequestDispatcher(java.lang.String path). 另一种是servletContext.getRequestDispatcher(java.lang.String path);不同之处在于:前面的方法支持相对路径,以'/'作为当前上下文的跟路径;后一种不支持后一种不支持相对路径。

    可以看到视图的渲染过程是把model包装成map形式通过request的属性带到服务器端。

  • 相关阅读:
    世界时钟国家中英文名称国家代码与北京的时差 一览
    拼写CAML查询的小工具
    The trust relationship between this workstation and the primary domain failed
    SharePoint 2003 架构介绍
    [经典文章翻译]垃圾收集: 在Microsoft .NET Framework中的自动化内存管理 第二部分
    [转] [精华] 跟我一起写 Makefile
    c#的常用排序
    MS SQL Server查询优化方法
    如何进行成功的创业程序员创业白皮书
    SQL编码规范
  • 原文地址:https://www.cnblogs.com/wdpnodecodes/p/7820295.html
Copyright © 2020-2023  润新知