Listing 7-1.View Interface Definition
public interface View {
void render(Map model, HttpServletRequest request,
HttpServletResponse response) throws Exception;
}
■NoteMany of Spring’s high-level interfaces consist only of a single method. This facilitates the maximum
amount of reuse from interfaces and makes them good candidates for anonymous inner class implementations.
The interface is simple. It says that, given a model and the servlet’s request and response
objects, a Viewwill generate, or render, the output. It assumes nothing else, and that means
you have the widest possible choice when selecting an implementation. As we’ll see later,
though, creating your own Viewimplementation is quite rare; more commonly you’ll use one
of the built-in Spring view types.
Implementing View
The render()method of the Viewinterface returns void. The buck stops here as far as Spring
MVC is concerned; it is the responsibility of the view not just to generate the content but to
actually return it to the client too, if appropriate.
We could, therefore, successfully implement a view with the example in Listing 7-2.
Listing 7-2.Example View Implementation
public class ModelIteratorView implements View {
public void render(Map model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
PrintWriter out = new PrintWriter(response.getOutputStream());
for (Object key : model.keySet()) {
out.print(key.toString());
out.print(" = ");
out.println(model.get(key));
}
out.flush();
out.close();
}
}
OK, so it won’t win your website any design awards, but you’re fulfilling the very basic
requirement of a View. Spring provides many implementations of Viewthat act as hooks for
the supported view technologies—for example, InternalResourceView(JSP), VelocityView,
AbstractXsltView,and others. We’ll cover the specifics of these and others in Chapter 8 as we
examine the major view technologies in more detail.
CHAPTER 7 ■THE VIEW LAYER 203