Dispatcher Servlet in Spring MVC

Dispatcher Servlet in Spring MVC

The Dispatcher Servlet is a core component in the Spring MVC framework and acts as the front controller in the MVC design pattern. Its primary responsibilities include:

1. Receiving Requests: It intercepts all incoming HTTP requests to the web application.

2. Delegating Requests: It determines which controller should handle the request by consulting the HandlerMapping.

3. Processing Requests: It dispatches the request to the appropriate controller method.

4. Returning Responses: It processes the controller’s output and determines the view that should render the response by consulting the ViewResolver.

The DispatcherServlet plays a crucial role in the workflow of a Spring MVC application, ensuring that the flow of requests and responses is managed efficiently.

Dispatcher Servlet

Java Example

Project Structure
 1. Project Structure
```
src
 └── main
     └── java
         └── com
             └── example
                 └── config
                     └── WebConfig.java
                 └── controller
                     └── HomeController.java
     └── resources
         └── application.properties
     └── webapp
         └── WEB-INF
             └── views
                 └── home.jsp
     └── web.xml
```

Maven Dependencies (pom.xml)
2. Maven Dependencies (pom.xml)
```xml
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.10</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
```

Web Configuration (WebConfig.java)
 3. Web Configuration (WebConfig.java)
```java
package com.example.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example.controller")
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/views/", ".jsp");
    }
}
```

Controller (HomeController.java)
 4. Controller (HomeController.java)
```java
package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("message", "Hello, Spring MVC!");
        return "home"; // returns the view name "home"
    }
}
```

View (home.jsp)
 5. View (home.jsp)
```jsp
<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <h1>${message}</h1>
</body>
</html>
```

web.xml Configuration
 6. web.xml Configuration
```xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
         http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" 
         version="4.0">
    
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.Dispatcher Servlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

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

Explanation of the Example:

  • 1. DispatcherServlet Configuration (web.xml):
    • The `Dispatcher Servlet` is configured in the `web.xml` file. It is initialized with a configuration file located at `/WEB-INF/spring/dispatcher-config.xml`.
    • It is mapped to intercept all requests (`/*`).

  • 2. WebConfig.java:
    • This is the Java-based configuration class. It enables Spring MVC (`@EnableWebMvc`) and specifies where to scan for components (`@ComponentScan`).
    • Configures the view resolver to look for JSP files in `/WEB-INF/views/`.

  • 3. HomeController.java:
    • This is a simple controller that handles HTTP GET requests to the root URL (`/`).
    • It adds a message to the model and returns the name of the view (`home`).

  • 4. home.jsp:   
    • This is the JSP file that renders the model data. It displays the message set by the controller

Homepage

Readmore