Spring Web MVC Overview

Spring Web MVC (Model-View-Controller) is the standard component for handling HTTP requests and responses within the Java EE ecosystem, built upon the Model2 design pattern. This framework achieves a high cohesion and low coupling modular architecture by decoupling three layers: business logic, view rendering, and controller execution. In modern development environments such as Spring Boot, Spring MVC remains the core skeleton of web applications, supporting various scenarios including RESTful API development and traditional form submissions.

Core Components and Workflow Process

Understanding how Spring MVC operates requires mastering its three core roles—the Controller, Model, and View—and their interaction flow: when a client initiates an HTTP request, Spring DispatcherServlet acts as the entry point for front-end controllers to receive it, subsequently delegating the task to specific Controllers. The Controller is responsible for processing business logic and returning either a ModelAndView object or a response containing only data.

The concrete workflow process includes:

  1. Request Dispatching: DispatcherServlet intercepts all HTTP requests originating from the web container.
  2. View Resolution: Through HandlerMapping (Handler Mapper), URLs are converted into specific Controller methods, while ViewResolver determines the type and name of the returned view.
  3. Model Population: After processing business logic, the Controller places data into a Model object for use by the view.
  4. View Rendering: DispatcherServlet invokes the corresponding View handler to generate HTML or other formatted content and return it to the client.

This process ensures clear layering of request handling, allowing developers to focus on implementing logic at specific layers without needing to worry about underlying details.

Controller Design and Annotation Support

In Spring MVC, Controller classes typically handle specific requests using static methods and define behavioral characteristics through a series of standard annotations. These annotations not only provide the convenience of declarative programming but also enhance code readability and maintainability. Common core annotations include @RestController, @RequestMapping, @GetMapping, as well as those related to parameter binding.

Key Annotation Explanations

  • @Controller: Marks a class as a controller component, usually used in conjunction with other annotations.
  • @ResponseBody: Indicates that the method's return value should be sent directly as HTTP response content rather than rendering a view.
  • @RequestMapping: Defines request mapping paths and processing rules (GET, POST, etc.).
  • @PathVariable / @RequestParam: Used to extract data from URLs or query parameters and inject it into method formal parameters.

The following example demonstrates a typical Controller implementation:

@RestController
@RequestMapping("/api/users")
public class UserController {

    @GetMapping("/{id}")
    public ResponseEntity<User> getUser(@PathVariable Long id) {
        User user = userService.findById(id);
        return new ResponseEntity<>(user, HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<Void> createUser(@RequestBody User user) {
        userService.save(user);
        return ResponseEntity.accepted().build();
    }
}

In this example, @RestController automatically combines the functionality of @Controller and @ResponseBody, allowing returned objects to be serialized directly into JSON. The parameter binding mechanism automatically performs type conversion on data from path variables or request bodies and assigns it to method formal parameters, greatly simplifying development work.

Exception Handling and Global Response Strategies

In production environments, a unified error handling approach is crucial for enhancing system robustness. Spring MVC provides the @ControllerAdvice (Controller Advisor) annotation to define global exception handlers, thereby avoiding repetitive try-catch logic in every Controller. By configuring HandlerMethodArgumentResolver and custom ExceptionClassResolvers, one can achieve capturing and formatting returns of specific business exceptions.

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
        ErrorResponse error = new ErrorResponse("NOT_FOUND", "Resource not found");
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
        // Log the exception and return a generic error message to avoid leaking internal details.
        ErrorResponse error = new ErrorResponse("INTERNAL_ERROR", "An unknown system error occurred");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
    }
}

This centralized exception handling mechanism not only reduces code redundancy but also ensures consistency in error response styles across different modules. Developers can focus on implementing business logic without needing to consider strategies for dealing with edge cases excessively.

View Resolution and Template Engine Integration

While JSON responses are often used directly in RESTful API development, Spring MVC offers powerful view resolution capabilities when rendering complex front-end pages is required. By configuring InternalResourceViewResolver or third-party template engines such as Thymeleaf or FreeMarker, dynamic content generation can be achieved. Thymeleaf has become one of the mainstream choices due to its excellent syntax sugar and performance characteristics.

To enable Thymeleaf in a Spring Boot application, add the following dependency:

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

By setting the view resolver name to application/web/resources/templates in the configuration file, Spring MVC can automatically locate corresponding .html files. Template engines support Expression Language (EL) and custom tags, allowing data binding and logical judgments to be embedded into HTML structures declaratively, significantly improving front-end and back-end interaction efficiency.