Dispatcher Servlet Java Configuration

Learn about an alternate way of configuring the dispatcher servlet using Java configuration.

The XML files web.xml and player-servlet.xml define the Spring MVC application configuration. It is possible to configure our application without using any XML. We will replace the files mentioned above with Java classes to initialize the dispatcher servlet.

First, we will create a package for the configuration files called config in io.datajek.springmvc. This package will contain two files that replace the web.xml and player-servlet.xml.

Defining the dispatcher servlet

The web.xml file (created while configuring Spring MVC Application - Part 1) defined the dispatcher servlet, provided the location of its config file, and set up the URL mapping. To perform the same functionality in Java, Spring provides an abstract class called AbstractAnnotationConfigDispatcherServletInitializer. This class has methods for specifying the root configuration class, dispatcher servlet configuration class and URL mapping.

We will provide an implementation of this class to define the dispatcher servlet and set up the URL mapping by creating a class MyDispatcherServletInitializer that extends AbstractAnnotationConfigDispatcherServletInitializer. It comes with the following unimplemented methods:

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.