Popular Searches
Popular Course Categories
Popular Courses

Configuring Spring MVC Applications

Configuring Spring MVC Applications

Spring MVC and Enterprise Web Development

Configuring Spring MVC Applications

Course: Advanced Java Training

Topic: Configuring Spring MVC Applications

Course Link: Advanced Java Training at JustAcademy

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to Spring MVC Configuration

Configuring a Spring MVC application involves setting up the components required to process HTTP requests, execute controller methods, manage application data, resolve views, and return responses to clients. Spring MVC is a web framework built on the Model-View-Controller design pattern.

Configuration connects different parts of the application, including the DispatcherServlet, controllers, handler mappings, view resolvers, validation components, and application services. A correctly configured application can process requests efficiently and maintain a clear separation between web handling, business logic, and presentation.

Spring MVC applications can be configured using Java-based configuration, XML configuration, or Spring Boot auto-configuration.

Learning Objectives

  • Understand the requirements for configuring a Spring MVC application.
  • Learn the role of DispatcherServlet and application contexts.
  • Configure Spring MVC using Java configuration.
  • Understand traditional XML-based configuration.
  • Register controllers and configure component scanning.
  • Configure view resolvers and static resources.
  • Understand request mapping, validation, and exception handling configuration.
  • Learn common configuration errors and troubleshooting techniques.

2. Prerequisites for Spring MVC Configuration

Before configuring a Spring MVC application, prepare the required development environment and project dependencies.

Requirement Description
Java Development Kit Provides the Java compiler and runtime. Java 17 or later is required for Spring Framework 6.
Maven or Gradle Manages dependencies and builds the application.
IDE IntelliJ IDEA, Eclipse, or another Java-compatible editor.
Spring Web MVC Provides DispatcherServlet, controller support, request mapping, and other MVC components.
Servlet Container Runs a traditional servlet-based application, such as a compatible Tomcat server.
View Technology JSP, Thymeleaf, or another supported presentation technology for server-rendered pages.
Database Driver Required when the application connects to a relational database.

Important: Spring Framework 6 uses Jakarta EE APIs, including jakarta.servlet. Older Spring 5 applications commonly use the javax.servlet namespace. Avoid mixing incompatible Spring versions and servlet APIs.

3. Understanding the Spring MVC Configuration Architecture

Spring MVC configuration establishes how incoming requests are received, mapped to controllers, processed, and converted into responses.

Client / Browser
       |
       | HTTP Request
       v
DispatcherServlet
       |
       v
HandlerMapping
       |
       v
HandlerAdapter
       |
       v
Controller
       |
       v
Service Layer
       |
       v
Repository / Database
       |
       v
Controller + Model
       |
       v
ViewResolver
       |
       v
View Template
       |
       | HTTP Response
       v
Client / Browser

The diagram represents a typical server-rendered application. REST controllers can instead write data directly to the response body, without requiring a server-side view resolver.

Core Configuration Components

  • DispatcherServlet: Receives requests and coordinates request processing.
  • ApplicationContext: Manages Spring beans and dependency injection.
  • Component scanning: Detects annotated controllers, services, and other Spring components.
  • HandlerMapping: Identifies the handler that matches a request.
  • ViewResolver: Resolves logical view names to configured view resources.
  • Resource handling: Defines how static files such as CSS, JavaScript, and images are served.
  • Exception handling: Defines how application errors are translated into appropriate responses.

4. Choosing a Configuration Approach

Spring MVC supports several configuration approaches. The best choice depends on the application's age, deployment model, and project requirements.

Approach Description Typical Use
Java-based configuration Uses Java classes and annotations to register and configure components. Modern traditional Spring MVC applications.
XML-based configuration Defines beans and web configuration in XML files. Legacy applications and projects that require XML configuration.
Spring Boot Uses auto-configuration, starter dependencies, and convention-based setup. Applications that benefit from simplified configuration and embedded servers.

5. Configuring Maven Dependencies

For a traditional Spring MVC application, add the Spring Web MVC dependency to the project's pom.xml file. The example below uses a Spring 6 release as an illustration; select a supported version compatible with your project.

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>6.2.0</version>
    </dependency>
</dependencies>

For a JSP-based application, additional dependencies and servlet-container configuration may be necessary. The Servlet API is generally provided by the target container in a traditional WAR deployment, so it is commonly declared with a provided scope.

When using Spring Boot, prefer the appropriate Spring Boot web starter and its dependency management instead of manually maintaining individual Spring Framework versions.

6. Java-Based Spring MVC Configuration

Java-based configuration defines Spring beans and MVC settings using Java classes. It reduces the need for XML and makes configuration easier to refactor and maintain.

6.1 Create the Configuration Class

The @Configuration annotation marks a class as a source of bean definitions. The @EnableWebMvc annotation enables Spring MVC infrastructure in a traditional Spring MVC application.

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.WebMvcConfigurer;

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

6.2 Understanding the Annotations

Annotation or Interface Purpose
@Configuration Declares a class that provides Spring bean definitions.
@EnableWebMvc Enables Spring MVC configuration and infrastructure.
@ComponentScan Scans specified packages for annotated Spring components.
WebMvcConfigurer Provides callback methods for customizing MVC configuration.
@Bean Declares an object managed by the Spring container.

7. Registering DispatcherServlet

In a traditional servlet-based Spring MVC application, DispatcherServlet must be registered with the servlet container. One approach is to use a Java initializer that registers the servlet and supplies the Spring configuration.

package com.example.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebAppInitializer
        extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

Explanation:

  • getRootConfigClasses() supplies configuration for the root application context, often used for services and repositories. It returns null here because this example keeps configuration simple.
  • getServletConfigClasses() supplies configuration for the DispatcherServlet's application context.
  • getServletMappings() maps the DispatcherServlet to the root URL pattern.

This initializer approach is intended for a traditional servlet-container deployment. Spring Boot applications normally register DispatcherServlet automatically, so they do not generally require this initializer.

```html

8. Configuring ViewResolver

A ViewResolver maps a logical view name returned by a controller to an actual view resource. It is commonly used in server-rendered Spring MVC applications that use JSP or another view technology.

Example: JSP ViewResolver Configuration

@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver resolver =
            new InternalResourceViewResolver();

    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");

    return resolver;
}

With this configuration, when a controller returns "home", Spring resolves the view to /WEB-INF/views/home.jsp.

Controller Example

@Controller
public class HomeController {

    @GetMapping("/home")
    public String home(Model model) {
        model.addAttribute("message", "Welcome to Spring MVC");
        return "home";
    }
}

The controller adds a message to the model and returns the logical view name. The ViewResolver identifies the JSP file responsible for rendering the response.

9. Configuring Static Resources

Static resources include CSS files, JavaScript files, images, fonts, and other files that do not need to be generated dynamically by a controller.

When DispatcherServlet is mapped to /, it can handle requests that would otherwise be served by the servlet container's default servlet. Spring MVC can be configured to serve static resources from specified locations.

Java Configuration Example

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**")
            .addResourceLocations("/resources/");
}

For example, a CSS file located at /resources/css/style.css can be requested using a URL such as /resources/css/style.css, relative to the application's context path.

Why Static Resource Configuration Matters

  • Allows browsers to load stylesheets and JavaScript files.
  • Supports images and other presentation assets.
  • Separates static files from controller processing.
  • Helps organize web application resources.

10. Configuring XML-Based Spring MVC

XML-based configuration is commonly found in older Spring MVC applications. It defines application beans, component scanning, MVC infrastructure, and view resolution in XML files.

10.1 Example Spring MVC XML Configuration

Create a configuration file named spring-mvc.xml.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.example" />

    <mvc:annotation-driven />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

10.2 Explanation of XML Elements

Element Purpose
<beans> Defines the Spring bean configuration document.
<context:component-scan> Scans the specified package for annotated components.
<mvc:annotation-driven> Enables annotation-based MVC infrastructure.
<bean> Declares a Spring-managed object.
<property> Configures a property of a bean.

Note: The XML namespace configuration shown here is intended for traditional applications. Java-based configuration is generally preferable for new traditional Spring MVC projects. Spring Boot applications usually use auto-configuration.

11. Configuring Request Mappings

Request mappings connect incoming HTTP requests to controller methods. They can specify URL patterns, HTTP methods, request parameters, headers, and content types.

Example

@Controller
@RequestMapping("/students")
public class StudentController {

    @GetMapping
    public String listStudents(Model model) {
        model.addAttribute("message", "Student List");
        return "students";
    }

    @GetMapping("/{id}")
    public String getStudent(
            @PathVariable int id,
            Model model) {

        model.addAttribute("studentId", id);
        return "student-details";
    }

    @PostMapping
    public String createStudent() {
        return "student-success";
    }
}

In this example:

  • GET /students displays the student list.
  • GET /students/10 passes the path variable value 10 to the controller.
  • POST /students invokes the method responsible for handling student creation.

In a real application, the creation method should validate submitted data, invoke the service layer, and persist the student through an appropriate repository.

12. Configuring Dependency Injection

Dependency injection allows Spring to create and manage objects and supply their required dependencies. It reduces tight coupling between application components.

Service Example

import org.springframework.stereotype.Service;

@Service
public class StudentService {

    public String getStudentName() {
        return "Rahul";
    }
}

Injecting the Service into a Controller

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

@Controller
public class StudentController {

    private final StudentService studentService;

    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }

    @GetMapping("/student-name")
    public String showStudentName(Model model) {
        model.addAttribute(
            "studentName",
            studentService.getStudentName()
        );

        return "student-name";
    }
}

The service is registered as a Spring bean using @Service. Component scanning discovers the service and controller, while constructor injection supplies the service to the controller.

Benefits of Dependency Injection

  • Reduces tight coupling between classes.
  • Makes unit testing easier.
  • Supports reusable service components.
  • Centralizes object creation and lifecycle management.
  • Improves maintainability and application structure.

13. Configuring Form Validation

Form validation ensures that user-submitted information satisfies defined rules before business operations are performed. Spring MVC integrates with Jakarta Bean Validation implementations to validate form objects.

Example Form Object

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;

public class StudentForm {

    @NotBlank(message = "Name is required")
    private String name;

    @NotBlank(message = "Email is required")
    @Email(message = "Enter a valid email address")
    private String email;

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

Controller Validation Example

import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class RegistrationController {

    @GetMapping("/register")
    public String showForm(Model model) {
        model.addAttribute("studentForm", new StudentForm());
        return "register";
    }

    @PostMapping("/register")
    public String submitForm(
            @Valid @ModelAttribute("studentForm")
            StudentForm studentForm,
            BindingResult result) {

        if (result.hasErrors()) {
            return "register";
        }

        return "registration-success";
    }
}

The @Valid annotation triggers validation, and BindingResult provides access to validation errors. The BindingResult parameter should immediately follow the validated argument.

For validation to work, include a compatible Jakarta Bean Validation implementation in the project dependencies.

14. Configuring Exception Handling

Exception handling allows an application to respond appropriately when errors occur during request processing. Spring MVC supports local exception handlers using @ExceptionHandler and application-wide handling through @ControllerAdvice.

Example

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public String handleException(
            Exception exception,
            Model model) {

        model.addAttribute(
            "message",
            "An unexpected error occurred."
        );

        return "error";
    }
}

This example provides a common error view for unhandled exceptions that reach the advice handler. Production applications should use more specific exception handlers where appropriate, log diagnostic details securely, and return suitable HTTP status codes.

Advantages

  • Centralizes common error-handling logic.
  • Reduces repeated exception-handling code.
  • Supports consistent error responses.
  • Helps avoid exposing sensitive internal details to users.

15. Configuring Spring MVC Interceptors

An interceptor can execute logic before or after a controller handler runs. Interceptors are useful for request logging, timing, and selected request-processing concerns.

Example Interceptor

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class LoggingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) {

        System.out.println(
            "Request URI: " + request.getRequestURI()
        );

        return true;
    }
}

Registering the Interceptor

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LoggingInterceptor())
            .addPathPatterns("/students/**");
}

Register this method inside the application's WebMvcConfigurer implementation. The interceptor will apply to matching student-related routes.

For authentication and authorization, prefer Spring Security rather than relying on a custom MVC interceptor as the primary security mechanism.

16. Configuring Spring MVC in Spring Boot

Spring Boot simplifies Spring MVC setup by providing auto-configuration and starter dependencies. It normally configures DispatcherServlet and common MVC infrastructure automatically.

Example Maven Dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Example Controller

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

@Controller
public class WelcomeController {

    @GetMapping("/welcome")
    public String welcome(Model model) {
        model.addAttribute("message", "Welcome to Spring Boot MVC");
        return "welcome";
    }
}

For server-rendered JSP applications, additional view dependencies and packaging considerations may apply. Thymeleaf is another common option for Spring Boot applications.

Customizing MVC in Spring Boot

You can implement WebMvcConfigurer to customize selected MVC features without replacing Boot's default MVC configuration.

@Configuration
public class CustomMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/assets/**")
                .addResourceLocations("classpath:/static/assets/");
    }
}

When using Spring Boot, do not add @EnableWebMvc unless you intentionally want to take control of Spring MVC configuration and replace Boot's MVC auto-configuration behavior.

17. Common Configuration Errors and Solutions

Error Possible Cause Solution
404 Not Found Incorrect URL or missing request mapping. Verify controller annotations, servlet mapping, and application context path.
Controller not detected Component scanning excludes the controller package. Configure the correct base package in @ComponentScan.
View not found Incorrect view resolver prefix, suffix, or resource location. Check the logical view name and actual template path.
HTTP 405 Request uses an unsupported HTTP method. Check the method mapping and client request type.
Validation does not run Missing validation implementation or incorrect controller parameter setup. Check dependencies, @Valid, and BindingResult.
Static resources fail to load Incorrect resource mapping or file location. Check resource handlers and browser network requests.
Dependency injection fails Missing bean definition or incorrect package scanning. Verify component annotations and constructor dependencies.
Servlet API errors Incompatible Java, Spring, or servlet API versions. Align Spring Framework, Java, Jakarta Servlet, and container versions.

18. Spring MVC Configuration Best Practices

  • Choose Java-based configuration for most new traditional Spring MVC applications.
  • Use Spring Boot auto-configuration when it suits the project's requirements.
  • Keep controllers, services, and repositories in clearly organized packages.
  • Use constructor injection for required dependencies.
  • Configure view resolution explicitly when using a traditional server-rendered application.
  • Validate user input and handle binding errors properly.
  • Use centralized exception handling for consistent error responses.
  • Configure static resource paths carefully and apply suitable caching policies.
  • Keep sensitive configuration outside source code when appropriate.
  • Use Spring Security for authentication and authorization.
  • Write integration tests for important request mappings and configuration.
  • Ensure all dependencies and servlet APIs are compatible.

19. Practical Project: Student Registration Application

Objective: Build a Spring MVC application that accepts student details, validates submitted data, and displays a success page.

Project Requirements

  1. Create a Maven project with the required Spring MVC dependencies.
  2. Configure DispatcherServlet using a Java initializer or the chosen framework's supported setup.
  3. Create a WebConfig class for MVC configuration and component scanning.
  4. Create a StudentForm class with name and email validation rules.
  5. Create a StudentController with GET and POST request mappings.
  6. Create a registration form using JSP or another supported view technology.
  7. Display validation errors when the submitted form contains invalid data.
  8. Display a success page after successful validation.
  9. Test URL mappings, view resolution, and form submission.

Expected Learning Outcomes

  • Understand how Spring MVC configuration connects application components.
  • Register and configure DispatcherServlet.
  • Use controller mappings to process requests.
  • Transfer form data through model objects.
  • Validate input and handle errors.
  • Resolve views and render responses.

20. Interview Questions and Answers

Q1. What does configuring a Spring MVC application mean?

Answer: It means setting up the components and infrastructure required for request handling, controller registration, dependency injection, view resolution, resource handling, and application responses.

Q2. What is the purpose of DispatcherServlet?

Answer: DispatcherServlet is the front controller that receives incoming requests and coordinates handler selection, execution, exception handling, and view rendering.

Q3. What is the purpose of @EnableWebMvc?

Answer: It enables Spring MVC configuration in a Java-based traditional Spring MVC application and registers the required MVC infrastructure.

Q4. What is WebMvcConfigurer?

Answer: WebMvcConfigurer provides methods for customizing Spring MVC features, including static resources, interceptors, formatters, CORS, and other web configuration options.

Q5. How is DispatcherServlet registered in a traditional application?

Answer: It can be registered using a servlet initializer, a servlet-container deployment descriptor, or another supported servlet configuration mechanism.

Q6. What is the difference between Java and XML configuration?

Answer: Java configuration defines beans and MVC settings through Java classes and annotations, while XML configuration defines them through XML elements and properties.

Q7. Why is component scanning important?

Answer: Component scanning discovers annotated components such as controllers and services so Spring can register and manage them as beans.

Q8. What is the role of a ViewResolver?

Answer: It maps logical view names returned by controllers to actual view resources in server-rendered applications.

Q9. How can static resources be configured?

Answer: Static resource handlers can map URL patterns to locations containing CSS, JavaScript, images, and other static files.

Q10. Should @EnableWebMvc be used in every Spring Boot application?

Answer: No. Spring Boot normally configures Spring MVC automatically. Adding @EnableWebMvc changes the default auto-configuration behavior and should be done only when intentional.

Q11. How can form data be validated?

Answer: Use Jakarta Bean Validation annotations on form objects, apply @Valid to the controller parameter, and inspect validation errors through BindingResult.

Q12. How can global exceptions be handled?

Answer: Use @ControllerAdvice with suitable @ExceptionHandler methods to centralize exception handling across controllers.

21. Quick Revision Checklist

  • Spring MVC supports Java-based and XML-based configuration.
  • Spring Boot provides MVC auto-configuration.
  • DispatcherServlet is the central request-processing component.
  • @Configuration defines Spring configuration classes.
  • @EnableWebMvc enables MVC infrastructure in traditional applications.
  • @ComponentScan discovers annotated components.
  • WebMvcConfigurer customizes MVC behavior.
  • ViewResolver maps logical view names to actual views.
  • Resource handlers configure static files.
  • Dependency injection connects controllers and services.
  • Validation protects application workflows from invalid input.
  • Exception handling improves error consistency.
  • Compatible Java, Spring, and servlet versions are essential.

22. Conclusion

Configuring Spring MVC applications is an essential skill for Java web development. It involves connecting the DispatcherServlet, application contexts, controllers, services, view resolvers, resource handlers, validation components, and exception handlers into a functioning web application.

Java-based configuration provides a flexible approach for traditional Spring MVC projects, XML remains relevant for maintaining legacy applications, and Spring Boot simplifies common configuration requirements through auto-configuration.

By practising these configuration techniques, developers can build web applications that are organized, testable, maintainable, and easier to troubleshoot.

Explore the Advanced Java Training course at JustAcademy to learn more about Java web development and Spring technologies.

Visit the JustAcademy official website or register for a course demo to explore training opportunities.

Previous Next
whatsapp