DispatcherServlet
DispatcherServlet is at the heart of Spring MVC and explained earlier implements the Front Controller pattern in line with other famous web application framework like Struts and JSF. It handles all the incoming requests and is responsible for coordinating the request-handling activities with the Spring MVC framework.
Figure 14-7 below pictorially represents the working of DispatcherServlet in the context of Spring MVC framework. As you can see from the figure below, DispatcherServlet even though handles all the requests it delegates various tasks to other components and gets the work done.
Figure 14-7. Working of DispatcherServlet in Spring MVC
The DispatcherServlet is configured in the web deployment descriptor (web.xml) as shown in Listing 14-1 below.
Listing 14-1. Configuring DispatcherServlet in web.xml file
1 2 3 4 5 6 7 8 9 10 11 |
… <servlet> <servlet-name>sample</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>sample</servlet-name> <url-pattern>/app/*</url-pattern> </servlet-mapping> … |
The servlet name is very important as Spring loads the context from /WEB-INF/<servlet-name>-context.xml file, where <servlet-name> in this case is “sample”. That means the Spring context file will be /WEB-INF/sample-context.xml.
It is very important to know in detail as to how the Spring loads the application context file in a web environment. Figure 14-8 below shows the context hierarchy in Spring MVC.
Figure 14-8. Context hierarchy in Spring MVC
The DispatcherServlet when initialized looks for a file name <servlet-name>-context.xml in the WEB-INF directory of your web application and loads all the beans defined there in. Each DispatcherServlet has its own so called WebApplicationContext which is very much similar to ApplicationContext but differs in having some extra features relevant for web applications. The context configuration file in Spring MVC can be configured in multiple ways as shown in Listing 14-2 and Listing 14-3. You also have an option of combing the two options and load the context configuration file. It’s very much important to know the visibility of various beans when loading the context configuration files.
Page Visitors: 7466


Tomcy John


Latest posts by Tomcy John (see all)
- A Guide to Continuous Improvement for Architects - February 2, 2023
- Cloud-first Architecture Strategy - January 26, 2023
- Architecture Strategy and how to create One - January 24, 2023