Expert Spring MVC and Web Flow

(Dana P.) #1
HandlerAdapter
The org.springframework.web.servlet.HandlerAdapteris a system level interface, allowing
for low coupling between different request handlers and the DispatcherServlet. Using this
interface, the DispatcherServletcan interact with any type of request handler, as long as a
HandlerAdapteris configured.

■Tip If your application consists of only Controllers, then you may safely ignore this section.Controllers
are supported by default, and no explicit configurations for HandlerAdapters are required. However, read on if
you are interested in integrating a third-party framework into Spring MVC.

Why not just require all request handlers to implement some well-known interface? The
DispatcherServletis intended to work with any type of request handler, including third-party
frameworks. Integrating disparate software packages is often difficult because the source code
isn’t available or is very difficult to change. The Adapter design pattern attempts to solve this
problem by adapting the third party’s interface to the client’s expected interface. The seminal
book Design Patterns(Gamma, Helm, Johnson, and Vlissides; Addison Wesley, 1995) defines
this pattern’s goal as follows: “Convert the interface of a class into another interface clients
expect. Adapter lets classes work together that couldn't otherwise because of incompatible
interfaces.”
Spring’s HandlerAdapterachieves this adaptation by delegation. Listing 5-3 shows the
HandlerAdapterinterface.

Listing 5-3.HandlerAdapter Interface

package org.springframework.web.servlet;

public interface HandlerAdapter {

boolean supports(Object handler);

ModelAndView handle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception;

long getLastModified(HttpServletRequest request, Object handler);

}

The DispatcherServletwill check whether the HandlerAdaptersupports a handler type
with a call to supports(). If so, the DispatcherServletwill then ask the adapter to delegate the
request to the handler via the handle()method. Notice how this interface is provided the
handler instead of looking one up via the ApplicationContext.
If your application uses only Controllers, which nearly all Spring MVC applications
do, then you will never see this interface. It is intended, along with its default subclass
SimpleControllerHandlerAdapter, to be used by the framework internally. However, if

84 CHAPTER 5 ■THE PROCESSING PIPELINE

Free download pdf