1. Overview

The DispatcherServlet is the front controller in Spring web applications. It’s used to create web applications and REST services in Spring MVC. In a traditional Spring web application, this servlet is defined in the web.xml file.

In this tutorial, we’ll migrate code from a web.xml file to DispatcherServlet in a Spring Boot application. Also, we’ll map Filter, Servlet, and Listener classes from web.xml to the Spring Boot application.

2. Maven Dependency

First, we have to add the spring-boot-starter-web Maven dependency to our pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

3. DispatcherServlet

DispatcherServlet receives all of the HTTP requests and delegates them to controller classes.

Before the Servlet 3.x specification, DispatcherServlet would be registered in the web.xml file for a Spring MVC application. Since the Servlet 3.x specification, we can register servlets programmatically using ServletContainerInitializer.

Let’s see a DispatcherServlet example configuration in the web.xml file:

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Spring Boot provides the spring-boot-starter-web library for developing web applications using Spring MVC. One of the main features of Spring Boot is autoconfiguration. The Spring Boot autoconfiguration registers and configures the DispatcherServlet automatically. Therefore, we don’t need to register the DispatcherServlet manually.

By default, the spring-boot-starter-web starter configures DispatcherServlet to the URL pattern “/”. So, we don’t need to complete any additional configuration for the above DispatcherServlet example in the web.xml file. However, we can customize the URL pattern using server.servlet.* in the application.properties file:

server.servlet.context-path=/demo
spring.mvc.servlet.path=/baeldung

With these customizations, DispatcherServlet is configured to handle the URL pattern /baeldung and the root contextPath will be /demo. Thus, DispatcherServlet listens at http://localhost:8080/demo/baeldung/.

#spring-boot #java #programming #developer

DispatcherServlet and web.xml in Spring Boot
35.20 GEEK