Skip to content

A comprehensive guide to Spring MVC 7.0+ configuration showcasing the evolution from XML-based descriptors and Java-based initializers to Spring Boot auto-configuration.

License

Notifications You must be signed in to change notification settings

harman-04/spring-mvc-configuration-xml-vs-java-based-annotation-approach

Repository files navigation

Spring MVC Mastery: Multi-Configuration Deep Dive

This project is a comprehensive guide to understanding the evolution of Spring MVC configuration. It demonstrates three distinct ways to set up a Spring Web application: Traditional XML-based, Modern Java-based, and Spring Boot (Embedded).


Project Structure & File Purpose

File Path Purpose
pom.xml Root Manages dependencies (Spring MVC 7, Jakarta Servlet 6, JSTL).
web.xml src/main/webapp/WEB-INF/ The "Deployment Descriptor" for XML-based configuration.
spring-servlet.xml src/main/resources/ Spring's XML context file for beans, scanning, and view resolution.
WebConfig.java org.spring.mvc.configuration Java-based replacement for spring-servlet.xml.
SpringMvcApplication.java org.spring.mvc.configuration The application entry point (Hybrid Initializer).
HelloController.java org.spring.mvc.configuration Handles web requests and returns data/views.
home.jsp src/main/webapp/WEB-INF/views/ The final HTML page rendered to the user.

Configuration Approaches

1. XML-Based Configuration (Traditional)

This approach relies on the Servlet Container (Tomcat) reading web.xml.

  • Key File: web.xml inside WEB-INF.
  • Key Concept: DispatcherServlet. This is the "Front Controller" that intercepts all requests (/).
  • How it Works: * web.xml uses <init-param> to point to spring-servlet.xml.
    • spring-servlet.xml uses <mvc:annotation-driven /> to enable @Controller and <context:component-scan> to find your classes.
    • View Resolver: The InternalResourceViewResolver bean prepends /WEB-INF/views/ and appends .jsp to view names.

2. Java-Based Configuration (Modern)

This removes XML entirely by using Java classes.

  • Key Interface: WebApplicationInitializer. This is a special interface that Tomcat scans for automatically.
  • Key Method: onStartup(ServletContext container). It programmatically registers the DispatcherServlet.
  • Key Class: WebConfig.java with @Configuration and @EnableWebMvc.
  • How it Works: Instead of an XML file, we register the WebConfig.class into an AnnotationConfigWebApplicationContext.

3. Spring Boot Approach (Current Standard)

The most automated way to run Spring.

  • Key Annotation: @SpringBootApplication. It triggers auto-configuration, component scanning, and property loading.
  • Key Method: SpringApplication.run(). It starts an Embedded Tomcat server inside the JAR/WAR.
  • Hybrid Bridge: The @ImportResource("classpath:/spring-servlet.xml") allows you to use a Boot application while still loading old XML bean definitions.

Code Breakdown: Detailed Method Analysis

HelloController.java

  • @Controller: Marks the class as a web handler.
  • @GetMapping("/"): Maps HTTP GET requests for the root URL to this method.
  • ModelAndView: A container for both the Model (the data like "message") and the View (the JSP name "home").

WebConfig.java

  • implements WebMvcConfigurer: Allows us to customize how Spring MVC works (like setting up View Resolvers).
  • configureViewResolvers(): Tells Spring exactly where to find the UI files so the controller can just return "home" instead of the full path.

SpringMvcApplication.java (The Initializer)

  • extends SpringBootServletInitializer: Allows a Spring Boot app to be deployed as a standard WAR on an external Tomcat.
  • onStartup(): This is the heart of Java-based config. It manually "plugs" Spring into the Servlet container.

Detailed Class & Concept Reference

1. Java-Based Configuration (Classes & Interfaces)

Component Concept / Purpose Location
WebApplicationInitializer An interface used to configure the ServletContext programmatically. It is the Java-based alternative to web.xml. SpringMvcApplication.java
AnnotationConfigWebApplicationContext A specialized Spring container for web environments that accepts @Configuration classes as input. SpringMvcApplication.java
DispatcherServlet The "Front Controller" of Spring MVC. It intercepts all incoming HTTP requests and dispatches them to controllers. SpringMvcApplication.java / web.xml
ServletRegistration.Dynamic A Jakarta Servlet API class used to programmatically register and configure servlets (like DispatcherServlet) in the container. SpringMvcApplication.java
WebMvcConfigurer An interface that provides callback methods to customize the Java-based configuration for Spring MVC (e.g., View Resolvers). WebConfig.java
InternalResourceViewResolver A class that resolves "logical" view names (like "home") into physical resources (like /WEB-INF/views/home.jsp). WebConfig.java / spring-servlet.xml
ModelAndView A holder for both Model data and the View name, allowing a controller to return both in one return value. HelloController.java
SpringBootServletInitializer A class that allows a Spring Boot application to run when deployed as a WAR file on an external Tomcat server. SpringMvcApplication.java

2. Annotation Reference

  • @Configuration: Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions.
  • @EnableWebMvc: Enables default Spring MVC configurations (similar to <mvc:annotation-driven /> in XML).
  • @ComponentScan: Tells Spring where to look for @Controller, @Service, and @Component classes.
  • @Controller: Stereotype annotation marking a class as a web request handler.
  • @GetMapping("/"): Specialized version of @RequestMapping specifically for HTTP GET requests at the root path.
  • @ImportResource: A hybrid annotation used to load existing XML configurations into a Java-based context.

XML Tag Reference

web.xml (The Deployment Descriptor)

  • <servlet>: Defines the DispatcherServlet as the entry point for the web application.
  • <init-param>: Passes parameters to the servlet. contextConfigLocation tells Spring where to find its XML configuration.
  • <load-on-startup>: Ensures the servlet is initialized as soon as the server starts, rather than waiting for the first request.
  • <servlet-mapping>: Maps the servlet to a URL pattern (/ means all requests).

spring-servlet.xml (Spring Context)

  • <mvc:annotation-driven />: Enables sophisticated features like formatting, validation, and JSON support.
  • <context:component-scan>: Automatically detects controllers in the specified package.
  • <bean class="...InternalResourceViewResolver">: Manually defines the View Resolver bean to locate JSP files.

How to Use & Switch Modes

To Test This Mode Step 1: SpringMvcApplication.java Step 2: web.xml
XML Mode Comment out onStartup and remove extends. Keep in WEB-INF folder.
Java Mode Uncomment onStartup and implements WebApplicationInitializer. Rename web.xml to web.xml.bak.
Boot Mode Uncomment @SpringBootApplication and run() method. Ignored by Boot.

️ Critical Troubleshooting: The 404 Fix

  • Location Rule: The web.xml must be inside src/main/webapp/WEB-INF/. If it is in the root of webapp, Tomcat 11 will not see it.
  • Namespace Rule: For Jakarta EE 10+ (Tomcat 10/11), use the jakarta.servlet namespace, not javax.servlet.
  • View Path: Ensure your JSPs are inside WEB-INF/views/ so they are protected from direct browser access.

Dependencies Analysis (pom.xml)

  • spring-webmvc: The core library for the MVC pattern.
  • jakarta.servlet-api: Essential for interacting with the Tomcat server.
  • tomcat-embed-jasper: Required only for Spring Boot mode to compile JSPs.
  • jakarta.servlet.jsp.jstl: Allows logic (like loops and conditionals) inside your JSP pages.

Required Folder Structure

src/main
├── java/org/spring/mvc/configuration/
│   ├── HelloController.java     (Requests)
│   ├── SpringMvcApplication.java(Initialization)
│   └── WebConfig.java           (Java Config)
├── resources/
│   └── spring-servlet.xml       (XML Config)
└── webapp/
    └── WEB-INF/
        ├── web.xml              (Entry Point)
        └── views/
            └── home.jsp         (UI)

About

A comprehensive guide to Spring MVC 7.0+ configuration showcasing the evolution from XML-based descriptors and Java-based initializers to Spring Boot auto-configuration.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages