18.3 The ViewRendererServlet

The rendering process in Portlet MVC is a bit more complex than in Web MVC. In order to reuse all the view technologies from Spring Web MVC), we must convert the PortletRequest / PortletResponse to HttpServletRequest / HttpServletResponse and then call the render method of the View. To do this, DispatcherPortlet uses a special servlet that exists for just this purpose: the ViewRendererServlet.

In order for DispatcherPortlet rendering to work, you must declare an instance of the ViewRendererServlet in the web.xml file for your web application as follows:

<servlet>
    <servlet-name>ViewRendererServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.ViewRendererServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>ViewRendererServlet</servlet-name>
    <url-pattern>/WEB-INF/servlet/view</url-pattern>
</servlet-mapping>

To perform the actual rendering, DispatcherPortlet does the following:

  1. Binds the WebApplicationContext to the request as an attribute under the same WEB_APPLICATION_CONTEXT_ATTRIBUTE key that DispatcherServlet uses.

  2. Binds the Model and View objects to the request to make them available to the ViewRendererServlet.

  3. Constructs a PortletRequestDispatcher and performs an include using the /WEB- INF/servlet/view URL that is mapped to the ViewRendererServlet.

The ViewRendererServlet is then able to call the render method on the View with the appropriate arguments.

The actual URL for the ViewRendererServlet can be changed using DispatcherPortlet’s viewRendererUrl configuration parameter.