Java Reference
In-Depth Information
Solution
Deploy a servlet to act as a single common gateway for all web requests. This servlet is
called the front controller servlet. Sometimes this pattern is also referred to as Gateway
Servlet.
Strategies with the Spring Framework
The Spring MVC framework provides an out-of-the box front controller servlet called
DispatcherServlet . This central servlet forms the backbone of the Spring MVC framework
and is integrated with the Spring IOC container. It is thus possible to get all the benefits
offered by the Spring IOC container.
The DispatcherServlet intercepts all web requests from the clients and routes them
to the appropriate page controllers. The page controllers are simple POJOs responsible
for interacting with the business layer components. These are registered in the Spring
container and implement the GOF command pattern. The page controllers will be dis-
cussed in detail later in this chapter. But in short, the front controller servlet and the
page controllers work together to form the core of an event-driven web application. The
front controller does not have any if-else blocks. All the code in the if-else block is
moved into page controllers. Hence, the front controller is a generic component that can
be reused across applications.
The front controller servlet delegates the responsibility of next-view selection and
binding the model object to specialized view managers. This allows the DispatcherServlet
to concentrate on a single responsibility: intercepting requests and then delegating the
rest of the functions to specialized handlers. Thus, the generic front controller helps
reduce the number of controllers. A single controller servlet should be sufficient for the
entire application. This is possible because the page controllers and view managers can
be made accessible to the front controller by simple configuration. However, some
designers also prefer to use one front controller per module. It is just a matter of choice,
but whatever the case, avoid multiple controllers per module.
Using the Front Controller
I will now show how to put the Spring DispatcherServlet to use. I will also discuss how to
refactor the bad-smelling JSP in the process. My preference is to use a single controller
for the entire application to minimize configuration maintenance overhead. As with all
servlets, the first step in using the DispatcherServlet is to configure it in the web.xml file.
The code in Listing 3-3 registers the front controller servlet with the web server.
 
Search WWH ::




Custom Search