Lesson

DispatcherServlet

spring/Spring Boot

DispatcherServlet in Spring

1. Introduction

DispatcherServlet is the main component of Spring MVC.

It acts as a front controller, meaning:

  • It receives all HTTP requests

  • Sends requests to the correct controller

  • Returns the response to the client


2. What DispatcherServlet Does

  • Handles incoming requests

  • Finds the correct controller

  • Executes business logic

  • Selects the correct view

  • Sends response back


3. Working Flow

Step 1: Request

  • Client sends HTTP request

  • DispatcherServlet receives it

Step 2: Handler Mapping

  • Finds which controller will handle the request

Step 3: Controller

  • Controller processes request

  • Returns data and view name

Step 4: Model and View

  • Model = data

  • View = page name

Step 5: View Resolver

  • Converts logical view name into actual file

Step 6: Response

  • Final output sent to client


4. Setup in Spring MVC (XML Based)


Step 1: Configure DispatcherServlet

plaintext
<servlet>
    <servlet-name>frontcontroller-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>frontcontroller-dispatcher</servlet-name>
    <url-pattern>/app/*</url-pattern>
</servlet-mapping>

Step 2: Create Configuration File


  • Create file inside WEB-INF


  • Example: frontcontroller-dispatcher-servlet.xml


Step 3: Run Application


  • Deploy on Tomcat


  • DispatcherServlet starts automatically


5. DispatcherServlet in Spring Boot

In Spring Boot, DispatcherServlet is auto-configured.

You do not need to define it manually.


Step 1: Create Spring Boot Project


  • Use Spring Initializr


  • Add dependency: Spring Web


Step 2: Model Class

plaintext
package com.example.demo.model;

public class Details {

    private int id;
    private String name;

    public Details(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Step 3: Controller Class

plaintext
package com.example.demo.controller;

import com.example.demo.model.Details;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api")
public class DetailsController {

    private List<Details> detailsList = new ArrayList<>();

    @GetMapping("/details")
    public List<Details> getAllDetails() {
        return detailsList;
    }

    @PostMapping("/details")
    public String addDetails(@RequestBody Details details) {
        detailsList.add(details);
        return "Data Inserted Successfully";
    }

    @PutMapping("/details/{id}")
    public String updateDetails(@PathVariable int id, @RequestBody Details updatedDetails) {
        for (Details details : detailsList) {
            if (details.getId() == id) {
                details.setName(updatedDetails.getName());
                return "Data Updated Successfully";
            }
        }
        return "Detail not found";
    }

    @DeleteMapping("/details/{id}")
    public String deleteDetails(@PathVariable int id) {
        detailsList.removeIf(details -> details.getId() == id);
        return "Data Deleted Successfully";
    }
}

Step 4: Main Class

plaintext
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Step 5: Optional Custom Configuration

plaintext
package com.example.demo.config;

import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;

@Configuration
public class WebConfig {

    @Bean
    public ServletRegistrationBean<DispatcherServlet> dispatcherServlet() {

        DispatcherServlet dispatcherServlet = new DispatcherServlet();

        ServletRegistrationBean<DispatcherServlet> registrationBean =
                new ServletRegistrationBean<>(dispatcherServlet);

        registrationBean.addUrlMappings("/api/*");

        return registrationBean;
    }
}

6. Key Points


  • DispatcherServlet is the core of Spring MVC


  • Acts as front controller


  • Handles request flow from start to end


  • In Spring Boot, it is auto-configured


7. Conclusion


  • DispatcherServlet simplifies request handling


  • Centralizes control in web applications


  • Essential for building Spring MVC and Spring Boot apps