Spring MVC & REST
Spring MVC is the web framework built on the Servlet API. In modern microservices, we mostly use it to build REST APIs.1. REST Controller Annotations
| Annotation | Purpose |
|---|---|
@RestController | Combines @Controller and @ResponseBody. |
@RequestMapping | Base path for the controller (e.g., /api/v1/users). |
@GetMapping, @PostMapping | Shortcuts for specific HTTP methods. |
@PutMapping, @DeleteMapping | Update and Delete mappings. |
@PathVariable | Extract values from the URI path (e.g., /users/{id}). |
@RequestParam | Extract query parameters (e.g., /users?role=admin). |
@RequestBody | Map the JSON body to a Java Object (POJO). |
@ResponseStatus | Set the HTTP status code (e.g., 201 CREATED). |
2. Building a User API
Let’s build a CRUD API for aUser resource.
The Domain Model (DTO)
3. Exception Handling with @ControllerAdvice
Don’t let raw stack traces leak to the client. Use global exception handling.4. Bean Validation
Never trust client input. Use Hibernate Validator (implementation of Jakarta Bean Validation). Add dependencyspring-boot-starter-validation.
Add Constraints to DTO
MethodArgumentNotValidException in your @RestControllerAdvice to return a nice list of validation errors.
5. Content Negotiation
Spring Boot usesJackson by default to serialize/deserialize Java Objects to JSON.
- If you want XML, add
jackson-dataformat-xmldependency. - Spring will check the
Acceptheader of the request to decide whether to return JSON or XML.
6. Internal Request Lifecycle (DispatcherServlet)
Spring MVC is designed around the Front Controller pattern. TheDispatcherServlet handles all incoming requests.
7. Filters vs Interceptors vs AOP
Interviewers love this question.| Feature | Filter | Interceptor | AOP |
|---|---|---|---|
| Layer | Servlet Container (Tomcat) | Spring MVC Framework | Spring Bean (Method Level) |
| Scope | Runs for ALL requests (even non-Spring) | Runs only for valid DispatcherServlet requests | Runs for method calls |
| Access | Raw ServletRequest / ServletResponse | HandlerMethod (Knows which controller is mapped) | Method Arguments & Return Value |
| Use Case | Security, GZip Compression, CORS | Auth Checks, Logging execution time | Transaction mgmt, Audit Logging |
Implementing an Interceptor
8. Asynchronous Requests
If an API takes 10 seconds, you don’t want to block a Tomcat thread (default ~200 threads) for 10s. CompletableFuture9. Spring Security Integration
Spring Security is simply a chain of standard Servlet Filters.
If
AuthenticationFilter fails (e.g., bad token), it throws an exception and the request never reaches the Controller.
10. Deep Dive: Spring Security Architecture
Spring Security is a lot more than just a few annotations.The Big Picture
- DelegatingFilterProxy: A standard Servlet Filter (registered with Tomcat) that delegates to a Spring Bean.
- FilterChainProxy: The Spring Bean that holds all security logic. It contains a list of SecurityFilterChains.
- SecurityFilterChain: A chain of filters matching a specific URL pattern.
The Authentication Flow
Key Components
- AuthenticationManager: The API that defines how Spring Security’s Filters perform authentication.
- ProviderManager: The standard implementation of
AuthenticationManager. It delegates to a list ofAuthenticationProviders. - AuthenticationProvider: Doing the actual work (e.g.,
DaoAuthenticationProvidertalks to DB,LdapAuthenticationProvidertalks to LDAP). - UserDetailsService: Interface to load user-specific data using a username.