Spring MVC & REST
Dashboard
Topic 29/30
Home › Spring MVC & REST

🌐 Spring MVC & REST APIs

Build web applications and RESTful APIs using the Spring Web MVC framework.

1. What is Spring MVC?

Spring MVC (Model-View-Controller) is a sub-framework of the Spring Framework designed to build web applications. It implements the Model-View-Controller design pattern, separating the application into three distinct components:

  • Model: Encapsulates the application data and business logic.
  • View: Renders the data to the user (e.g., HTML, JSP, JSON, XML).
  • Controller: Processes user requests, interacts with the Model, and passes the result to the View.

At the heart of Spring MVC is the DispatcherServlet, which acts as the Front Controller. It receives all incoming HTTP requests and delegates them to the appropriate components for processing.

Request Flow in Spring MVC:
1. Client sends an HTTP Request.
2. DispatcherServlet receives the request.
3. DispatcherServlet consults the HandlerMapping to find the appropriate Controller method.
4. The Controller processes the request, builds a Model, and returns a View name.
5. DispatcherServlet uses the ViewResolver to find the actual View template.
6. The View renders the model data and returns the HTTP Response to the client.
Note: In REST APIs, steps 4, 5, and 6 are simplified—the Controller returns data directly as JSON/XML using HttpMessageConverters.

2. @Controller vs @RestController

Spring provides two main annotations for defining controllers depending on the type of application you are building.

  • @Controller: Primarily used for traditional web applications where a view (like HTML/JSP) is returned. To return data (e.g., JSON), you must add @ResponseBody to the method.
  • @RestController: A convenience annotation that combines @Controller and @ResponseBody. It implies that every method returns a domain object instead of a view, making it perfect for REST APIs.
GreetingController.java Java

3. Request Mapping

Spring MVC binds HTTP requests to specific controller methods using @RequestMapping and its shortcut variants.

  • @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping
  • @PathVariable: Extracts values from the URI path (e.g., /users/123).
  • @RequestParam: Extracts values from query parameters (e.g., /users?page=1).
  • @RequestHeader: Extracts values from HTTP headers.
  • @RequestBody: Deserializes the incoming HTTP request body (JSON/XML) into a Java object.
MappingDemoController.java Java

4. ResponseEntity

While you can return objects directly from a @RestController (resulting in a default 200 OK status), it is often better to use ResponseEntity. It gives you full control over the HTTP status code, headers, and body.

ResponseEntityDemo.java Java

5. Complete REST API – Employee Management

Let's build a complete REST API managing Employees. We will include a Model, Repository (simulated), Service, and Controller.

Employee.java (Model) Java

6. Request Validation

Spring MVC makes it easy to validate incoming JSON using the Java Bean Validation API. First, include the spring-boot-starter-validation dependency.

  • @NotNull, @NotBlank: Ensure the field is present and not empty.
  • @Size(min=X, max=Y): Set length boundaries.
  • @Min, @Max: Numeric constraints.
  • @Email: Validate email formats.

Add @Valid before the @RequestBody in your controller to trigger validation.

EmployeeDto.java Java

7. Global Exception Handling

Instead of scattering try-catch blocks, use @ControllerAdvice and @ExceptionHandler to handle exceptions globally across all controllers.

GlobalExceptionHandler.java Java

8. Content Negotiation

Spring MVC can serve different data formats (JSON, XML) based on the client's Accept header. JSON is supported by default via Jackson. For XML, you need to add jackson-dataformat-xml to your pom.xml or build.gradle.

ContentNegotiationDemo.java Java

9. File Upload & Download

Spring provides the MultipartFile interface for uploading files. For downloading, return a Resource with the proper Content-Disposition header.

FileController.java Java

10. API Versioning Strategies

When evolving your API, you need to support old clients while introducing new features. Here are common strategies:

Strategy Implementation Example Pros & Cons
URI Versioning /api/v1/users
/api/v2/users
Easy to cache, intuitive. However, clutters URI space.
Parameter Versioning /api/users?version=1 Clean URI. Can be harder for routing.
Header Versioning Header: X-API-Version: 1 Clean URI. Harder to test manually in browser.
VersioningDemo.java Java

11. CORS Configuration

Cross-Origin Resource Sharing (CORS) is a security mechanism. By default, browsers block API requests made from a different domain. You must explicitly configure CORS in Spring.

Method Level: Use @CrossOrigin(origins = "http://localhost:3000") directly on a Controller or method.

Global Configuration: Implement WebMvcConfigurer.

CorsConfig.java Java

12. Interceptors

Spring Interceptors allow you to hook into the request processing lifecycle. You can execute code before a request reaches the controller, after the controller logic but before view rendering, or after the entire request completes.

They are useful for logging, security checks, modifying headers, etc.

LoggingInterceptor.java Java