Open In App

Spring – Configure Dispatcher Servlet in Three Different Ways

Improve
Improve
Like Article
Like
Save
Share
Report

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: 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. (With reference to the below image)

Dispatcher Servlet

 

So now you 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. You can use that front controller in your Spring MVC project. You really not required to create a front controller but you 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 we are going to see how can we configure Dispatcher Servlet in the following three different ways:

  1. Configure Dispatcher Servlet in web.xml File
  2. Configure Dispatcher Servlet using WebApplicationInitializer
  3. Configure Dispatcher Servlet using AbstractAnnotationConfigDispatcherServletInitializer

Way 1: Configure Dispatcher Servlet in web.xml File

In Spring, the /WEB-INF/web.xml file is the Web Application Deployment Descriptor of the application. This file is an XML document that defines everything about your application that a server needs to know except the context path, which is assigned by the Application Deployer and Administrator when the application is deployed, servlets and other components like filters or listeners, initialization parameters, container-managed security constraints, resources, welcome pages, etc. Refer to the below image to know where the web.xml file is located when we can create a Dynamic Web Project in Spring Tool Suite.

web.xml File

 

Inside this file, we have to configure our front controller inside a <servlet>…</servlet> tag something like this. 

<servlet>
    <!-- Provide a Servlet Name -->
    <servlet-name>frontcontroller-dispatcher</servlet-name>
    <!-- Provide a fully qualified path to the DispatcherServelt class -->
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>

Now let’s tell this servlet, hey servlet you have to handle all the requests coming to our website called gfg.com (for this example). So the way we are going to tell the above servlet is we can write something like this

<servlet-mapping>
    <!-- Provide a Servlet Name that you want to map -->
    <servlet-name>frontcontroller-dispatcher</servlet-name>
    <!-- Provide a url pattern -->
    <url-pattern>/gfg.com/*</url-pattern>
</servlet-mapping>

So this does mean that the servlet “frontcontroller-dispatcher” is going to handle all the requests starting from gfg.com/anything, that may be gfg.com/save or gfg.com/get, anything. But it must start with gfg.com. So we are done with configuring a Dispatcher Servlet. And the Dispatcher Servlet will be Initialized once we deploy the created dynamic web application inside the tomcat server. So before deploying it let’s add the following line inside the web.xml file 

<load-on-startup>1</load-on-startup>

And the above piece of code makes sure that whenever your server will get started the DispatcherServlet will get initialized. And if you are not writing this line of code then whenever the first request will come to your server starting from /student.com at that time only the DispatcherServlet will be initialized and we don’t want it. We want the DispatcherServlet will be initialized during the time of the server startup. That’s why we have written this line of code.

File: web.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                            http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
 
<display-name>myfirst-mvc-project</display-name>
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    <welcome-file>default.htm</welcome-file>
</welcome-file-list>
 
<servlet>
    <!-- Provide a Servlet Name -->
    <servlet-name>frontcontroller-dispatcher</servlet-name>
    <!-- Provide a fully qualified path to the DispatcherServelt class -->
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
 
<servlet-mapping>
    <!-- Provide a Servlet Name that you want to map -->
    <servlet-name>frontcontroller-dispatcher</servlet-name>
    <!-- Provide a url pattern -->
    <url-pattern>/student.com/*</url-pattern>
</servlet-mapping>
 
</web-app>


Tip: One must be aware of to adhering forward how to Configure Dispatcher Servlet in the web.xml File prior to adhering forward. 

Way 2: Configure Dispatcher Servlet using WebApplicationInitializer

In Spring, WebApplicationInitializer is an Interface and it is Servlet 3.0+ implementation to configure ServletContext programmatically in comparison to the traditional way to do this using the web.xml file. This interface is used for booting Spring web applications. WebApplicationInitializer registers a Spring DispatcherServlet and creates a Spring web application context. Traditionally, Java Web Applications based on Servlets were using the web.xml file to configure a Java Web Application. Since Servlet 3.0, web applications can be created programmatically via Servlet context listeners.

To configure Dispatcher Servlet using WebApplicationInitializer at first create an src/main/java folder and inside this folder create a class (here we have named CalculatorApplicationInitializer) and put it inside some package (here com.geeksforgeeks.calculator.config package) and implement the WebApplicationInitializer interface for which one can refer to the below media as follows:

 

Now in this class, we have to perform the following 2 major operations as listed below as follows: 

  1. Create a dispatcher servlet object
  2. Register Dispatcher Servlet with Servlet Context

And we can do it by writing these lines of code

Operation 1: Create a dispatcher servlet object

XmlWebApplicationContext webApplicationContext = new XmlWebApplicationContext();

// Create a dispatcher servlet object
DispatcherServlet dispatcherServlet = new DispatcherServlet(webApplicationContext);

Operation 2: Register Dispatcher Servlet with Servlet Context

ServletRegistration.Dynamic myCustomDispatcherServlet = servletContext.addServlet("myDispatcherServlet",
                dispatcherServlet);

This is the class where we have followed the Code-based Approach with WebApplicationInitializer. 

File: CalculatorApplicationInitializer.java

Java




// Java Program to Illustrate
// CalculatorApplicationInitializer Class
 
package com.geeksforgeeks.calculator.config;
 
// Importing required classes
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
 
// Class
public class CalculatorApplicationInitializer
    implements WebApplicationInitializer {
 
    // Method
    public void onStartup(ServletContext servletContext)
        throws ServletException
    {
 
        XmlWebApplicationContext webApplicationContext
            = new XmlWebApplicationContext();
 
        // Putting the spring configuration XML file
        webApplicationContext.setConfigLocation(
            "classpath:application-config.xml");
 
        // Creating a dispatcher servlet object
        DispatcherServlet dispatcherServlet
            = new DispatcherServlet(webApplicationContext);
 
        // Registering Dispatcher Servlet
        // with Servlet Context
        ServletRegistration
            .Dynamic myCustomDispatcherServlet
            = servletContext.addServlet(
                "myDispatcherServlet", dispatcherServlet);
 
        // Setting load on startup
        myCustomDispatcherServlet.setLoadOnStartup(1);
 
        // Adding mapping URL
        myCustomDispatcherServlet.addMapping("/gfg.com/*");
    }
}


Tip: One must be well aware of WebApplicationInitializer in Spring prior to moving ahead for better understanding.

Way 3: Configure Dispatcher Servlet using AbstractAnnotationConfigDispatcherServletInitializer

In this approach, we can Configure Dispatcher Servlet in Just Two Lines of Code. Create an src/main/java folder and inside this folder create a class (here we have named CalculatorAppInitializer) and put it inside some package (here com.geeksforgeeks.calculator.config package) and extends the AbstractAnnotationConfigDispatcherServletInitializer class for which one can refer to the below image as follows:

 

And whenever you are extending this class, it has some pre abstract methods that we need to provide the implementation. So now the CalculatorAppInitializer.java file is looking something like this.

File: CalculatorAppInitializer.java

Java




// Java Program to Demonstrate CalculatorAppInitializer Class
 
package com.geeksforgeeks.calculator.config;
 
// Importing required classes
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
 
// Class
public class CalculatorAppInitializer
    extends AbstractAnnotationConfigDispatcherServletInitializer {
 
    // Method
    @Override protected Class<?>[] getRootConfigClasses()
    {
        return null;
    }
 
    // Method
    @Override protected Class<?>[] getServletConfigClasses()
    {
        return aClass;
    }
 
    // Method
    @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: We 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: We 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.geeksforgeeks.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

package com.geeksforgeeks.calculator.config;

// Importing required classes
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

// Class
@Configuration
@ComponentScan(basePackages
               = "com.geeksforgeeks.calculator.controllers")
public class CalculatorAppConfig {}

Below is the complete code for the CalculatorAppInitializer.java file.

File: CalculatorAppInitializer.java

Tip: Do go through how to Configure Dispatcher Servlet in Just Two Lines of Code in Spring.

Henceforth in this way, you can configure Dispatcher Servlet in Spring. 



Last Updated : 02 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads