Spring MVC

·

11 min read

Lets understand Servlet Container before understanding SpringMVC

What is a Servlet Container?

A servlet container (also known as a web container) is a part of a web server or application server that provides the environment for running Java Servlets and managing their lifecycle. It acts as an intermediary between the client (usually a web browser) and the servlet-based Java application.

Key Responsibilities of a Servlet Container

  1. Servlet Lifecycle Management:

    • Creates and initializes servlet instances (init method).

    • Handles servlet requests and invokes the service method.

    • Destroys the servlet (destroy method) when no longer needed.

  2. Request and Response Handling:

    • Manages HTTP requests from clients and forwards them to the appropriate servlets.

    • Sends the HTTP response back to the client.

  3. Thread Management:

    • Handles multiple requests concurrently by assigning threads to servlets.
  4. Deployment:

    • Reads the deployment descriptor (web.xml) or annotations to configure servlets, filters, and listeners.
  5. Session Management:

    • Tracks client sessions (e.g., using cookies or URL rewriting).

Spring MVC and the Servlet Container

In a Spring MVC application:

  1. Servlet Container Startup:

    • The container starts and loads the web.xml configuration or the Spring Boot auto-configuration.
  2. ContextLoaderListener:

    • Creates the root ApplicationContext (global beans).
  3. DispatcherServlet Initialization:

    • The container initializes the DispatcherServlet, which creates the WebApplicationContext (web-specific beans).
  4. Request Handling:

    • The container routes HTTP requests to the DispatcherServlet.

what is web.xml

The web.xml file, also known as the deployment descriptor, is a configuration file used in traditional Java web applications to define how the application should be deployed and which components should be configured. It is part of the Servlet Specification and resides in the WEB-INF directory of a web application.


Spring MVC

Spring MVC (Model-View-Controller) is a part of the Spring Framework, designed to simplify the development of web applications by implementing the MVC design pattern. It provides a robust framework for building web applications that are loosely coupled, scalable, and testable. Here's a quick guide:

Core Components of Spring MVC

  1. Model
    Represents the application's data and business logic. It is often populated by services and contains data to be displayed in the view.

  2. View
    Responsible for rendering the data to the user. Spring supports various view technologies like JSP, Thymeleaf, and FreeMarker.

  3. Controller
    Handles user requests, interacts with the model, and selects the appropriate view to render.

Spring MVC Workflow

  1. Request Handling:

    • A DispatcherServlet acts as the front controller.

    • Routes requests to the appropriate controller.

  2. Controller Logic:

    • Controllers process requests and interact with the model.
  3. View Rendering:

    • The logical view name returned by the controller is resolved to a specific view.
  4. Response Generation:

    • The view is rendered and sent back to the client.

DispatcherServlet

The DispatcherServlet is a core component of Spring MVC and acts as the Front Controller for handling all incoming HTTP requests in a Spring MVC application. It coordinates the request processing by delegating to various other components, such as controllers, view resolvers, and exception handlers, to ensure a clean separation of concerns and streamlined request flow.

Role of DispatcherServlet

  1. Request Handling: Intercepts all incoming requests mapped to it (usually via a URL pattern like /*).

  2. Request Routing: Delegates requests to the appropriate controller based on handler mappings.

  3. Response Rendering: Coordinates the selection of a view and renders the response back to the client.

Lifecycle of a Request in DispatcherServlet

  1. Receive Request: The web container passes the HTTP request to the DispatcherServlet.

  2. Handler Mapping: DispatcherServlet consults the HandlerMapping to find the appropriate controller.

  3. Handler Adapter: The HandlerAdapter invokes the controller.

  4. Controller Execution: The controller processes the request and returns a ModelAndView object.

  5. View Resolution: The ViewResolver resolves the logical view name to a specific view.

  6. Render Response: DispatcherServlet instructs the resolved view to render the response to the client.

HandlerMapping, HandlerAdapter, ViewResolver

HandlerMapping, HandlerAdapter, and ViewResolver are not servlets. Instead, they are Spring framework components (interfaces and classes) that work behind the scenes in conjunction with the DispatcherServlet to process requests in a Spring MVC application. They play specific roles in the request-handling workflow but are not directly part of the servlet API.

  • These components are Java classes/interfaces defined by the Spring MVC framework.

  • They are managed as Spring beans in the Spring Application Context, meaning you can configure, customize, or extend them.

  • They implement well-defined interfaces to fit into Spring's request-processing lifecycle.

1. HandlerMapping

  • What it is:

    • An interface (org.springframework.web.servlet.HandlerMapping) responsible for mapping an incoming HTTP request to a handler (typically a controller).
  • How it works:

    • Based on the request URL, it determines which controller or handler method should handle the request.

    • Examples of implementations:

      • RequestMappingHandlerMapping: Maps @RequestMapping annotations to handler methods.

      • SimpleUrlHandlerMapping: Maps URL patterns to controllers using XML configuration.

  • Notable methods:

    • getHandler(HttpServletRequest request): Determines the handler for the given request.

2. HandlerAdapter

  • What it is:

    • An interface (org.springframework.web.servlet.HandlerAdapter) that acts as a bridge between the DispatcherServlet and the handler (controller).
  • How it works:

    • It invokes the appropriate method on the handler (e.g., a controller) based on the request.

    • Examples of implementations:

      • RequestMappingHandlerAdapter: Supports @RequestMapping annotated methods.

      • HttpRequestHandlerAdapter: Invokes custom handlers that implement HttpRequestHandler.

  • Notable methods:

    • handle(HttpServletRequest request, HttpServletResponse response, Object handler): Executes the handler logic and returns a ModelAndView.

3. ViewResolver

  • What it is:

    • An interface (org.springframework.web.servlet.ViewResolver) responsible for resolving logical view names returned by controllers into actual view implementations.
  • How it works:

    • Converts a view name (e.g., hello) into an actual view (e.g., /WEB-INF/views/hello.jsp or a Thymeleaf template).

    • Examples of implementations:

      • InternalResourceViewResolver: Resolves JSP files.

      • ThymeleafViewResolver: Resolves Thymeleaf templates.

  • Notable methods:

    • resolveViewName(String viewName, Locale locale): Resolves the logical view name into a View object.

Example of How These Components Work Together

  1. HandlerMapping:

    • Incoming request: GET /hello

    • RequestMappingHandlerMapping maps it to the sayHello method in HelloController.

  2. HandlerAdapter:

    • Invokes the sayHello method in HelloController.
  3. ViewResolver:

    • The controller returns the view name hello.

    • InternalResourceViewResolver resolves hello to /WEB-INF/views/hello.jsp.

  4. DispatcherServlet:

    • Renders /WEB-INF/views/hello.jsp as the response to the client.

Managed as Beans

Here’s how these components can be explicitly defined in a Spring configuration file:

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

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Bean
    public RequestMappingHandlerMapping handlerMapping() {
        return new RequestMappingHandlerMapping();
    }

    @Bean
    public RequestMappingHandlerAdapter handlerAdapter() {
        return new RequestMappingHandlerAdapter();
    }
}

All these components—HandlerMapping, HandlerAdapter, ViewResolver, and others—operate under the umbrella of DispatcherServlet, but they are not part of the DispatcherServlet itself. Instead, they are Spring-managed beans that the DispatcherServlet interacts with to handle the request lifecycle.

To put it simply: DispatcherServlet is the orchestrator. It relies on these components to process requests and generate responses.

How DispatcherServlet Works with These Components

  1. Request Handling Workflow:

    • When a request is sent to the DispatcherServlet, it takes the following steps:

      1. Look up HandlerMapping: Finds the right controller for the request URL.

      2. Delegate to HandlerAdapter: Calls the controller method (or other handler) to process the request.

      3. Handle Exceptions (if any): If an exception occurs, consults exception resolvers.

      4. Use ViewResolver: Resolves the logical view name to the actual view.

      5. Render the View: Renders the view to generate the response.

  2. Components Exist in the DispatcherServlet’s Context:

    • The DispatcherServlet creates its own WebApplicationContext, separate from the main application context (if any).

    • All MVC-related beans (like HandlerMapping, HandlerAdapter, ViewResolver) reside in this context.

WebApplicationContext

The WebApplicationContext is a specialized version of the ApplicationContext in the Spring Framework, specifically designed for web applications. It serves as the central container for managing beans and configuration in a Spring MVC web application.

What is ApplicationContext?

Before diving into WebApplicationContext, let’s recap ApplicationContext:

  • It is the central interface for accessing Spring-managed beans.

  • It provides features like dependency injection, internationalization, event propagation, and bean lifecycle management.

  • Examples of ApplicationContext implementations:

    • ClassPathXmlApplicationContext

    • AnnotationConfigApplicationContext

What is WebApplicationContext?

The WebApplicationContext extends the capabilities of ApplicationContext to add features specific to web applications, such as:

  1. Integration with Servlets:

    • It provides a way to access the servlet context (ServletContext), which is essential for web-based components.
  2. Web-Specific Scopes:

    • Supports additional bean scopes like request, session, and application.
  3. Access to Web Environment:

    • Handles web-related components like HandlerMapping, HandlerAdapter, ViewResolver, etc.

Hierarchy of WebApplicationContext

In a Spring MVC application, the WebApplicationContext typically exists in a hierarchical structure:

  1. Root ApplicationContext:

    • Created at application startup.

    • Shared across the entire application.

    • Contains beans for non-web-specific functionality, like services and repositories.

  2. Servlet-Specific WebApplicationContext:

    • Created by each DispatcherServlet.

    • Contains web-specific beans like controllers, view resolvers, and handler mappings.

    • Has access to beans in the root context.

Visual Representation

Root ApplicationContext
    |
    |-- Shared Beans (e.g., Services, Repositories)
    |
    `-- WebApplicationContext (DispatcherServlet's Context)
           |
           |-- MVC Components (Controllers, ViewResolvers, etc.)

Where Does DispatcherServlet Lie?

  1. DispatcherServlet and Application Context

    • The DispatcherServlet is a special front controller in Spring MVC.

    • It does not directly use the generic ApplicationContext. Instead, it interacts with a WebApplicationContext, which is a child context of the root ApplicationContext.

  2. Root Context vs. Servlet-Specific Context

    • Spring supports a hierarchy of contexts in a web application:

      • Root ApplicationContext:

        • Created by ContextLoaderListener during application startup.

        • Contains beans that are shared across the entire application (e.g., services, repositories).

      • Servlet-specific WebApplicationContext:

        • Created by the DispatcherServlet.

        • Contains web-related beans, such as controllers, handler mappings, and view resolvers.

The DispatcherServlet relies on the WebApplicationContext for managing its MVC-related beans.


What is Spring Boot higher level

Spring Boot is a framework built on top of the Spring Framework that simplifies the process of creating stand-alone, production-grade Spring-based applications. It eliminates the need for extensive XML configuration and provides an easy-to-use setup for building Java applications with minimal setup.

Key Features of Spring Boot:

  1. Auto-Configuration:

    • Automatically configures Spring beans based on the project's dependencies. For example, if you add a dependency for a database, Spring Boot will automatically configure the necessary data source, connection pool, etc.
  2. Standalone Applications:

    • Spring Boot allows you to package your application as a self-contained executable JAR or WAR, which can be run using a simple java -jar command without needing an external server like Tomcat.
  3. Embedded Servers:

    • It comes with embedded servlet containers such as Tomcat, Jetty, and Undertow. You don’t need to deploy to an external server like in traditional Spring MVC.
  4. Simplified Project Setup:

    • It reduces boilerplate configuration and allows developers to focus on business logic rather than setup.
  5. Spring Boot Starters:

    • It provides predefined configurations called starters (e.g., spring-boot-starter-web for building web applications).
  6. Production-Ready Features:

    • Built-in production-ready features such as health checks, metrics, application properties, etc.

DispatcherServlet in Spring Boot

Spring Boot does use the DispatcherServlet, but in a slightly different way compared to a traditional Spring MVC application. Let's clarify how the DispatcherServlet works in both contexts.

Spring Boot and DispatcherServlet:

  1. Spring Boot:

    • In a Spring Boot application, you typically don't have to manually configure the DispatcherServlet in a web.xml or servlet-context.xml file, as you would in a traditional Spring MVC application.

    • Spring Boot automatically configures the DispatcherServlet for you when you create a web application by including the spring-boot-starter-web dependency.

    • The DispatcherServlet is automatically registered as part of the embedded servlet container (like Tomcat, Jetty, or Undertow), so you don't need to set up an external servlet container or configure the DispatcherServlet explicitly.

  2. How It Works:

    • When you run a Spring Boot application, it creates an embedded servlet container and automatically configures the DispatcherServlet as the front controller for handling HTTP requests.

    • Spring Boot's auto-configuration will set up the DispatcherServlet to map incoming HTTP requests to the appropriate controllers in your application, just like in a typical Spring MVC application.

    • By default, the DispatcherServlet will be mapped to the root (/) URL path, which means it will handle all incoming requests unless you specify otherwise.

DispatcherServlet in REST API

DispatcherServlet is still responsible when developing REST APIs in Spring Boot, just as it is when developing traditional web applications. However, the role of the DispatcherServlet in the context of REST APIs is slightly different from that in a typical Spring MVC application.

Role of DispatcherServlet in Spring Boot REST APIs:

  1. Request Routing:

    • The DispatcherServlet is still the front controller for handling all HTTP requests, including RESTful requests.

    • It receives HTTP requests (like GET, POST, PUT, DELETE), matches them to appropriate controllers and methods annotated with @RequestMapping, @GetMapping, @PostMapping, etc.

  2. Mapping to REST Controllers:

    • In a REST API, you typically create controllers annotated with @RestController or @Controller (with @ResponseBody). These controllers handle HTTP requests and return JSON or XML responses.

    • The DispatcherServlet maps the incoming HTTP requests to these REST controller methods based on URL patterns (via annotations like @RequestMapping or @GetMapping).

  3. No View Resolution in REST:

    • In traditional Spring MVC applications, the DispatcherServlet would typically resolve views (e.g., JSP pages, Thymeleaf templates) to generate HTML responses.

    • However, in a REST API, the DispatcherServlet does not resolve views. Instead, it processes the request and directly returns the data (typically in JSON or XML format) via @ResponseBody or similar annotations.