DispatcherServlet acts as the Front Controller for Spring-based web applications. So now what is Front Controller? So it is pretty simple. Any request is going to come into our website the front controller is going to stand in front and is going to accept all the requests and once the front controller accepts that request then this is the job of the front controller that it will make a decision that who is the right controller to handle that request. For example, refer to the below image.
Suppose we have a website called student.com and the client is making a request to save student data by hitting the following URL student.com/save, and its first comes to the front controller and once the front controller accepts that request it is going to assign to the Controller_1 as this controller handle the request for /save operation. Then it is going to return back the response to the Client.
So now we might be thinking about how to create a front controller in a Spring MVC Application? But the good news is, the front controller is already created by the Spring Framework Developer, and the name of that particular controller is DispatcherServelt. We can use that front controller in your Spring MVC project. One is really not required to create a front controller but we can reuse that front controller created by the Spring Framework Developer and they named it as DispatcherServelt. We can say
DispatcherServlet handles an incoming HttpRequest, delegates the request, and processes that request according to the configured HandlerAdapter interfaces that have been implemented within the Spring application along with accompanying annotations specifying handlers, controller endpoints, and response objects.
Here are going to see the easiest way to configure Dispatcher Servlet in a Spring Application with the help of AbstractAnnotationConfigDispatcherServletInitializer class. We can do it by writing just two lines of code.
Implementation:
It is as shown below sequentially stepwise
Step 1: Set up the project
Note: We are going to use Spring Tool Suite 4 IDE for this project. Please refer to this article to install STS on your local machine How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
Go to your STS IDE then create a new maven project, File > New > Maven Project, and choose the following archetype as shown in the below image as follows:
Step 2: Adding Some Maven Dependencies
Add the following maven dependencies and plugin to your pom.xml file.
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.18</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <!-- plugin --> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build>
Below is the complete code for the pom.xml file after adding these dependencies.
File: pom.xml
XML
< modelVersion >4.0.0</ modelVersion > < groupId >com.neveropen</ groupId > < artifactId >spring-calculator</ artifactId > < packaging >war</ packaging > < version >0.0.1-SNAPSHOT</ version > < name >spring-calculator Maven Webapp</ name > < dependencies > < dependency > < groupId >junit</ groupId > < artifactId >junit</ artifactId > < version >3.8.1</ version > < scope >test</ scope > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-webmvc</ artifactId > < version >5.3.18</ version > </ dependency > < dependency > < groupId >javax.servlet</ groupId > < artifactId >javax.servlet-api</ artifactId > < version >4.0.1</ version > < scope >provided</ scope > </ dependency > </ dependencies > < build > < finalName >spring-calculator</ finalName > < plugins > < plugin > < groupId >org.apache.maven.plugins</ groupId > < artifactId >maven-war-plugin</ artifactId > < version >2.6</ version > < configuration > < failOnMissingWebXml >false</ failOnMissingWebXml > </ configuration > </ plugin > </ plugins > </ build > </ project > |
Step 3: Configuring Dispatcher Servlet in barely two lines
Before moving into the coding part let’s have a look at the file structure in the below image.
So at first create an src/main/java folder and inside this folder create a class named CalculatorAppIntilizer and put it inside the com.neveropen.calculator.config package and extends the AbstractAnnotationConfigDispatcherServletInitializer class. Refer to the below image.
And whenever you are extending this class, it has some pre abstract methods that we need to provide the implementation.
File: CalculatorAppIntilizer.java
Java
// Java Program to Illustrate CalculatorAppIntilizer Class package com.neveropen.calculator.config; // Importing required classes import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; // Class public class CalculatorAppIntilizer extends AbstractAnnotationConfigDispatcherServletInitializer { // Method 1 @Override protected Class<?>[] getRootConfigClasses() { return null ; } // Method 2 @Override protected Class<?>[] getServletConfigClasses() { return aClass; } // Method 3 @Override protected String[] getServletMappings() { return arr; } } |
Now inside this class, we have to just write two lines of code to Configure the Dispatcher Servlet.
1st Line of Code: In the first line you have to write the code inside the getServletMappings() method for the configure mapping for the dispatcher servlet is something like this.
// Add mapping url @Override protected String[] getServletMappings() { String arr[] = { "/gfg.com/*" }; return arr; }
2nd Line of Code: In the second line you have to write the code inside the getServletConfigClasses() method to register the spring config class is something like this. And you are done with the Configuration of Dispatcher Servlet.
// Register the Spring Config File @Override protected Class<?>[] getServletConfigClasses() { Class aClass[] = { CalculatorAppConfig.class }; return aClass; }
Here CalculatorAppConfig class is our spring config file. So, go to the src/main/java folder and inside this folder create a class named CalculatorAppConfig and put it inside the com.neveropen.calculator.config package. Below is the code for the CalculatorAppConfig.java file. We have used the @Configuration and @ComponentScan annotation in this class.
File: CalculatorAppConfig .java
// Java Program to Illustrate CalculatorAppConfig Class package com.neveropen.calculator.config; // Importing required classes import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; // Class @Configuration @ComponentScan(basePackages = "com.neveropen.calculator.controllers") public class CalculatorAppConfig {}
And below is the complete code for the CalculatorAppIntilizer.java file. Comments are added inside the code to understand the code in more detail.
File: CalculatorAppIntilizer.java
Java
// Java Program to Implement CalculatorAppIntilizer Class package com.neveropen.calculator.config; // Importing required classes import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; // Class public class CalculatorAppIntilizer extends AbstractAnnotationConfigDispatcherServletInitializer { // Method 1 @Override protected Class<?>[] getRootConfigClasses() { return null ; } // Method 2 // Registering the Spring config file @Override protected Class<?>[] getServletConfigClasses() { Class aClass[] = { CalculatorAppConfig. class }; return aClass; } // Method 3 // Add mapping url @Override protected String[] getServletMappings() { String arr[] = { "/gfg.com/*" }; return arr; } } |
Now run your application to see whether the dispatcher servlet has been initialized or not. Refer to the below image.
And here you can see our dispatcher servlet has been initialized and “dispatcher” is the default name provided by the Spring.
Step 4: Create Controller and Test The Application
Go to the src/main/java folder and inside this folder create a class named GfgController and put it inside the com.neveropen.calculator.controllers package. Below is the code for the GfgController.java file.
File: GfgController.java file
Java
package com.neveropen.calculator.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class GfgController { @RequestMapping ( "/welcome" ) @ResponseBody public String helloGfg() { return "Welcome to Lazyroar!" ; } } |
Step 5: Run The Application
Now run your spring MVC application and hit the following URL
http://localhost:8080/spring-calculator/gfg.com/welcome
and we can see the output as shown in the below image and our application is working fine.