An Example


Each and every view technology has its pros and cons. Spring does not favor any particular view technology or implement one itself. It aims to work with any view technology, supporting the most popular options out of the box and enabling the implementation of custom view integration if required.

The fact that Spring's web MVC framework is view agnostic is a major strength, compared to competing frameworks such as Struts. This gives you complete freedom of choice when it comes to developing the front-end of a web application.

In Chapter 12, we discussed logical view names and how to resolve views using org.springframework.web.servlet.view.ViewResolvers. You've also briefly read about the View interface with its render() method. We will review the different implementation of the View and ViewResolver interfaces. For now, let's stick with a simple example. Consider the following objects shown in Figure 13-1.

image from book
Figure 13-1

The controller that follows (resembling the ViewShowController we saw in Chapter 12) retrieves a specific show and encapsulates it in a ModelAndView object. The logical view name used by the controller is show. This name will then be linked to a JavaServer Page and a FreeMarker template, the two view variations.

Show show = boxOffice.getShow(Long.parseLong(showId)); ModelAndView mav = new ModelAndView("showdetails"); mav.addObject("show", show); return mav;

The model has been created; the logical view name is specified. We will now review the basics of rendering a view displaying the name of a show. This involves the following steps:

  • Linking the logical view name to a view resource (JSP, FreeMarker template) using a ViewResolver

  • Creating the actual resource (the JSP or the .fm file)

We will also show you how to generate a PDF document using iText.

General Configuration

Regardless of the view technology being used, Spring will always use an org.springframework.web.servlet.ViewResolver to link the logical view name (in this case show) to that view technology, and to any resources needed to render the view (when combined with the model). This resource could, for example, be a JavaServer Page or a Velocity template. It could, however, just as well be a class in which you generate a PDF file.

The view listing all shows will contain links such as the following. These will allow users to select a specific show they want more information about:

 http://www.springframework.com/boxoffice/viewshow.html?id=254 

We haven't defined a HandlerMapping in our application context, which results in the default BeanNameUrlHandlerMapping being used. If we name our controller after the URL, it will be mapped correctly:

<bean name="/viewshow.html"      >   <property name="boxOffice"><ref bean="boxOffice"/></property> </bean>

JavaServer Pages

To construct a view using JavaServer Pages, we first define a view resolver in the web application context. The resolver here mentions a view class also supporting JSPs using the Java Standard Tag Library (JSTL):

<bean    >   <property name="prefix"><value>/WEB-INF/jsp</value></property>   <property name="suffix"><value>.jsp</value></property>   <property name="viewClass">     <value>       org.springframework.web.servler.view.JstlView     </value>   </property> </bean>

After we've declared a view resolver that will transform view names to JSP files (here located in the WEB-INF/jsp directory), we create a JSP called showdetails.jsp and we're done.

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>     <h1>Hi user!</h1> <p>   You’ve selected <c:out    in the genre called <c:out value="${show.genre.name}"/>. </p>

FreeMarker

We could easily switch our view technology to FreeMarker. Some view technologies need a special configurer to set up the templating engine rendering the pages. FreeMarker can be configured using the FreeMarkerConfigurer. After you have defined the configurer, you need to mention a view resolver and specify the view class:

<bean    >   <property name="templateLoaderPath">     <value>WEB-INF/fm/</value></property>   </property> </bean>     <bean    >   <property name="viewClass">     <value>       org.springframework.web.servlet.view.freemarker.FreeMarkerView     </value>   </property> </bean>

Together with the following FreeMarker template called showdetails.fm, located in the /WEB-INF/fm directory, the view will render a similar output to the original JSP:

<h1>Hi user!</h1> <p>   You’ve selected ${show.name}, which happens    ${show.genre.name}. </p>

Velocity configuration closely resembles the FreeMarker configuration in this example.

Generating PDFs Using iText

One of the libraries available to generate PDFs is iText (www.lowagie.com/iText). It supports the programmatic construction of PDF documents and has a capable and intuitive API. To include PDF views in your application, code a view class generating the PDF:

 import com.lowagie.text.Document; import com.lowagie.text.Paragraph;      import org.springframework.web.servlet.view.document.AbstractPdfView;      public class ViewShowPdf extends AbstractPdfView {        protected void buildPdfDocument(     Map model, Document doc, PdfWriter writer, HttpServletRequest request,      HttpServletResponse response)   throws Exception {          Show show = (Show)model.get("show");          StringBuffer buffy = new StringBuffer();     buffy.append(       "Hello user, you’ve selected ").       show.getName()).append(       " which happens to be in the genre called ").append(       show.getGenre().getName());          doc.add(new Paragraph(buffy.toString());   } }   

The class needs to be defined in the application context as follows:

 <bean name="showdetails"   /> 

To complete the picture, the showdetails view name must be linked to the bean we just defined. We define a BeanNameViewResolver to do so as follows:

 <bean    /> 

You've seen that all there is to changing a view is implementing the actual view resources themselves and changing the view resolver. There is no need to change controller or model, whatever the view: a key value proposition of Spring MVC. Before we move on and start exploring more of the functionality Spring provides to ease development of views, we'll discuss some things you must understand when choosing a view technology for a particular project.



Professional Java Development with the Spring Framework
Professional Java Development with the Spring Framework
ISBN: 0764574833
EAN: 2147483647
Year: 2003
Pages: 188

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net