Spring MVC
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
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.
Request and Response Handling:
Manages HTTP requests from clients and forwards them to the appropriate servlets.
Sends the HTTP response back to the client.
Thread Management:
- Handles multiple requests concurrently by assigning threads to servlets.
Deployment:
- Reads the deployment descriptor (
web.xml
) or annotations to configure servlets, filters, and listeners.
- Reads the deployment descriptor (
Session Management:
- Tracks client sessions (e.g., using cookies or URL rewriting).
Spring MVC and the Servlet Container
In a Spring MVC application:
Servlet Container Startup:
- The container starts and loads the
web.xml
configuration or the Spring Boot auto-configuration.
- The container starts and loads the
ContextLoaderListener:
- Creates the root ApplicationContext (global beans).
DispatcherServlet Initialization:
- The container initializes the
DispatcherServlet
, which creates the WebApplicationContext (web-specific beans).
- The container initializes the
Request Handling:
- The container routes HTTP requests to the
DispatcherServlet
.
- The container routes HTTP requests to the
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
Model
Represents the application's data and business logic. It is often populated by services and contains data to be displayed in the view.View
Responsible for rendering the data to the user. Spring supports various view technologies like JSP, Thymeleaf, and FreeMarker.Controller
Handles user requests, interacts with the model, and selects the appropriate view to render.
Spring MVC Workflow
Request Handling:
A
DispatcherServlet
acts as the front controller.Routes requests to the appropriate controller.
Controller Logic:
- Controllers process requests and interact with the model.
View Rendering:
- The logical view name returned by the controller is resolved to a specific view.
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
Request Handling: Intercepts all incoming requests mapped to it (usually via a URL pattern like
/*
).Request Routing: Delegates requests to the appropriate controller based on handler mappings.
Response Rendering: Coordinates the selection of a view and renders the response back to the client.
Lifecycle of a Request in DispatcherServlet
Receive Request: The web container passes the HTTP request to the DispatcherServlet.
Handler Mapping: DispatcherServlet consults the
HandlerMapping
to find the appropriate controller.Handler Adapter: The
HandlerAdapter
invokes the controller.Controller Execution: The controller processes the request and returns a
ModelAndView
object.View Resolution: The
ViewResolver
resolves the logical view name to a specific view.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).
- An interface (
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 theDispatcherServlet
and the handler (controller).
- An interface (
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 implementHttpRequestHandler
.
Notable methods:
handle(HttpServletRequest request, HttpServletResponse response, Object handler)
: Executes the handler logic and returns aModelAndView
.
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.
- An interface (
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 aView
object.
Example of How These Components Work Together
HandlerMapping:
Incoming request:
GET /hello
RequestMappingHandlerMapping
maps it to thesayHello
method inHelloController
.
HandlerAdapter:
- Invokes the
sayHello
method inHelloController
.
- Invokes the
ViewResolver:
The controller returns the view name
hello
.InternalResourceViewResolver
resolveshello
to/WEB-INF/views/hello.jsp
.
DispatcherServlet:
- Renders
/WEB-INF/views/hello.jsp
as the response to the client.
- Renders
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
Request Handling Workflow:
When a request is sent to the
DispatcherServlet
, it takes the following steps:Look up HandlerMapping: Finds the right controller for the request URL.
Delegate to HandlerAdapter: Calls the controller method (or other handler) to process the request.
Handle Exceptions (if any): If an exception occurs, consults exception resolvers.
Use ViewResolver: Resolves the logical view name to the actual view.
Render the View: Renders the view to generate the response.
Components Exist in the DispatcherServlet’s Context:
The
DispatcherServlet
creates its ownWebApplicationContext
, 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:
Integration with Servlets:
- It provides a way to access the servlet context (
ServletContext
), which is essential for web-based components.
- It provides a way to access the servlet context (
Web-Specific Scopes:
- Supports additional bean scopes like
request
,session
, andapplication
.
- Supports additional bean scopes like
Access to Web Environment:
- Handles web-related components like
HandlerMapping
,HandlerAdapter
,ViewResolver
, etc.
- Handles web-related components like
Hierarchy of WebApplicationContext
In a Spring MVC application, the WebApplicationContext
typically exists in a hierarchical structure:
Root ApplicationContext:
Created at application startup.
Shared across the entire application.
Contains beans for non-web-specific functionality, like services and repositories.
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?
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 aWebApplicationContext
, which is a child context of the rootApplicationContext
.
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:
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.
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.
- Spring Boot allows you to package your application as a self-contained executable JAR or WAR, which can be run using a simple
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.
Simplified Project Setup:
- It reduces boilerplate configuration and allows developers to focus on business logic rather than setup.
Spring Boot Starters:
- It provides predefined configurations called starters (e.g.,
spring-boot-starter-web
for building web applications).
- It provides predefined configurations called starters (e.g.,
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:
Spring Boot:
In a Spring Boot application, you typically don't have to manually configure the
DispatcherServlet
in aweb.xml
orservlet-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 thespring-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 theDispatcherServlet
explicitly.
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:
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.
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
).
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.