Spring MVC
Java framework based on MVC pattern for building robust and maintainable web applications with Spring Framework.
Updated on February 5, 2026
Spring MVC is a module of the Spring Framework that implements the Model-View-Controller pattern for building web applications in Java. It provides a flexible and decoupled architecture that clearly separates business logic, presentation, and application flow control. Spring MVC seamlessly integrates with the Spring ecosystem to handle dependency injection, security, and data access.
Fundamentals of Spring MVC
- DispatcherServlet: front controller servlet that intercepts all HTTP requests and routes them to appropriate controllers
- Controllers: components annotated with @Controller that handle requests and return views or data
- ViewResolvers: configurable mechanisms to resolve views (JSP, Thymeleaf, JSON) from returned names
- HandlerMappings: mapping system between URLs and controller methods via annotations or configuration
Benefits of Spring MVC
- Separation of concerns: clear MVC architecture facilitating maintenance and unit testing
- Configuration flexibility: support for annotation-based, XML, and Java config to adapt to all contexts
- Ecosystem integration: native compatibility with Spring Boot, Spring Security, Spring Data for complete stacks
- Multi-format support: transparent handling of JSON, XML, HTML via content negotiation and converters
- Testability: MockMvc enables testing controllers without starting an application server
Practical Spring MVC Controller Example
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping
public ResponseEntity<List<Product>> getAllProducts(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
Page<Product> products = productService.findAll(
PageRequest.of(page, size)
);
return ResponseEntity.ok()
.header("X-Total-Count", String.valueOf(products.getTotalElements()))
.body(products.getContent());
}
@GetMapping("/{id}")
public ResponseEntity<Product> getProduct(@PathVariable Long id) {
return productService.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Product createProduct(@Valid @RequestBody ProductDTO productDTO) {
return productService.create(productDTO);
}
@PutMapping("/{id}")
public ResponseEntity<Product> updateProduct(
@PathVariable Long id,
@Valid @RequestBody ProductDTO productDTO) {
return productService.update(id, productDTO)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteProduct(@PathVariable Long id) {
productService.delete(id);
}
@ExceptionHandler(ProductNotFoundException.class)
public ResponseEntity<ErrorResponse> handleProductNotFound(
ProductNotFoundException ex) {
ErrorResponse error = new ErrorResponse(
HttpStatus.NOT_FOUND.value(),
ex.getMessage()
);
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
}
}Implementation Steps
- Configure Spring Boot with spring-boot-starter-web to get Spring MVC automatically configured
- Create controllers with @RestController or @Controller depending on response type (JSON/HTML)
- Define routes with @RequestMapping, @GetMapping, @PostMapping and parameters with @PathVariable, @RequestParam
- Implement validation with @Valid and Bean Validation annotations on DTOs
- Configure interceptors and filters for cross-cutting concerns (logging, authentication, CORS)
- Set up exception handlers with @ExceptionHandler or @ControllerAdvice for centralized error management
- Test with MockMvc and @WebMvcTest to validate routes and serialization without full server
Pro Tip
Use @RestControllerAdvice to centralize exception handling and standardized error responses. Combine with ResponseEntityExceptionHandler to automatically intercept validation and standard HTTP errors, ensuring consistent and REST-compliant APIs.
Related Tools and Extensions
- Spring Boot: auto-configuration and embedded server for quick startup
- Spring Security: integration for authentication and authorization with Spring MVC filters
- SpringDoc OpenAPI: automatic API documentation generation based on controller annotations
- Thymeleaf: modern template engine for server-side HTML views
- Jackson: JSON serialization/deserialization configured by default in Spring MVC
- Hibernate Validator: Bean Validation implementation for request validation
- Spring HATEOAS: creating hypermedia REST APIs compliant with REST level 3 principles
Spring MVC remains the reference for building enterprise Java web applications thanks to its maturity, flexibility, and comprehensive ecosystem. Its well-defined MVC architecture facilitates team collaboration and long-term maintenance. Coupled with Spring Boot, it enables rapid development of performant and scalable REST APIs, meeting the requirements of modern microservices architectures while providing the robustness necessary for critical systems.

