1. What Is Spring MVC? Why Spring MVC?
Spring MVC (Model View Controller) is a web framework of Spring used to build web applications and REST APIs.
Without Spring MVC
Servlets → Manual Request Handling
↓
Manual URL Mapping
↓
Manual Response Generation → More Boilerplate
With Spring MVC
Request → Controller
↓
Business Logic
↓
Response → Less Boilerplate
MVC Architecture
Model
Application data & business logic — User, Order, Product, Employee, DTO, Entity
View
Responsible for displaying data — JSP, Thymeleaf, HTML, JSON, XML
Controller
Handles incoming requests, calls Service layer, returns View or JSON response
2. DispatcherServlet — Internal Request Flow
DispatcherServlet = Front Controller of Spring MVC. Receives every HTTP request and routes it to the appropriate controller.
Why DispatcherServlet: Central Request Handling, URL Routing, Validation, Exception Handling, View Resolution, Content Negotiation.
DispatcherServlet Request Flow
HTTP Request → DispatcherServlet
↓
HandlerMapping (finds controller) → HandlerAdapter (invokes controller)
↓
Controller → Service → Repository → Database
↓
Repository → Service → Controller
↓
ViewResolver / HttpMessageConverter → HTTP Response
Spring MVC Components
DispatcherServlet→Front Controller
HandlerMapping→Maps incoming URL to correct controller method — e.g. GET /users → UserController.getUsers()
HandlerAdapter→Invokes matched controller method, handles parameters/return values/annotations
Controller→Handles request
ViewResolver→Resolves logical view name into actual view — "home" → /WEB-INF/views/home.jsp (traditional MVC)
HttpMessageConverter→Converts object to/from JSON/XML
Spring MVC Lifecycle
Application Starts → DispatcherServlet Created
↓
Controller Beans Loaded
↓ Request Arrives
DispatcherServlet → HandlerMapping → HandlerAdapter → Controller
↓
Business Logic
↓
ViewResolver Or HttpMessageConverter → Response
3. @Controller vs @RestController
ReturnsView (JSP/Thymeleaf) — uses ViewResolver
Typical UseTraditional web applications (server-side views)
Combines@Controller + @ResponseBody
ReturnsJSON/XML directly, without ViewResolver — uses HttpMessageConverter
Typical UseREST APIs, Microservices
4. REST API Fundamentals
REST (Representational State Transfer) is an architectural style for building web services using the HTTP protocol.
REST API Flow
Client → HTTP Request → DispatcherServlet
↓
Controller → Service → Repository → Database
↓
Repository → Service → Controller → HttpMessageConverter
↓
JSON Response → Client
5. HTTP Mapping Annotations
| Annotation | HTTP Method | Used For | Example |
| @RequestMapping | Any (path, method, consumes, produces) | Map requests to controller/method | /reports |
| @GetMapping | GET | Retrieve Data | GET /users → return users |
| @PostMapping | POST | Create Resource | POST /users → create user |
| @PutMapping | PUT | Complete Resource Update | PUT /users/10 → replace user |
| @PatchMapping | PATCH | Partial Resource Update | PATCH /users/10 → update email only |
| @DeleteMapping | DELETE | Delete Resource | DELETE /users/10 → delete user |
@RequestMapping can define Path, HTTP Method, Consumes, Produces. @GetMapping etc. are shortcuts for @RequestMapping(method=...).
6. Request Data Extraction
@PathVariable→Reads value from URL Path — /users/{id} → id=10. Used for resource identifiers.
@RequestParam→Reads query parameter — /users?page=1 → page=1. Used for pagination, filtering, searching, sorting.
@RequestHeader→Reads an HTTP header — Authorization, Content-Type, Accept, X-Correlation-Id
@RequestBody→Converts JSON request into a Java Object (via Jackson)
@ModelAttribute→Form data / query parameters → Object
Request Data Sources
| Source | Annotation |
| URL Path | @PathVariable |
| Query Parameter | @RequestParam |
| Request Body | @RequestBody |
| HTTP Header | @RequestHeader |
@RequestBody Flow
Client Sends JSON → DispatcherServlet
↓
HttpMessageConverter → Jackson
↓
Java Object → Controller
7. ResponseEntity & @ResponseStatus
ResponseEntity
Purpose: customize the HTTP Response. Can control Status Code, Headers, and Response Body.
Benefits: Flexible Response, Better API Design, Explicit Status Handling.
ResponseEntity Flow
Controller → Create ResponseEntity
↓
Status + Headers + Body
↓
HttpMessageConverter → JSON Response
@ResponseStatus → returns a fixed HTTP status without needing a ResponseEntity (common uses: 404, 201, 204, 400).
8. Jackson & HttpMessageConverter
Jackson
JSON library used by Spring Boot for Serialization and Deserialization.
Serialization: Java Object → Jackson → JSON
Deserialization: JSON → Jackson → Java Object
HttpMessageConverter
Converts HTTP request/response between Java Objects and different formats — JSON, XML, Text, Binary.
9. Full Request-Response Lifecycle
HTTP Request → DispatcherServlet → Controller
↓
@RequestBody → DTO → Service
↓
Repository → Database → Entity
↓
DTO → ResponseEntity
↓
Jackson → JSON Response
10. Validation
Validation ensures incoming data is correct, complete and follows business rules before processing.
Without: Invalid Data → Database Errors → Application Failures. With: Validate Request → Accept Valid Data / Reject Invalid Data → Return Proper Error.
Validation Flow
Client Sends Request → @RequestBody
↓
@Valid / @Validated → Bean Validation
↓ Passed
Controller → Service → Response
↓ Failed
Validation Exception → Global Exception Handler → 400 Bad Request
Common Bean Validation Annotations
@NotNull→Value must not be null
@NotEmpty→Collection/String must not be empty
@NotBlank→String cannot be blank
@Size→Minimum / Maximum length
@Min / @Max→Minimum / Maximum value
@Positive / @Negative→Greater than / Less than zero
@Email→Valid email format
@Pattern→Regular expression match
@Past / @Future→Past date / Future date
@Valid vs @Validated & Validation Groups
Standard (JSR/Jakarta) Validation, Nested Validation, mostly used on @RequestBody DTOs
Spring-specific, supports Validation Groups, Method Parameter Validation, Class Level Validation — more flexible
Validation Groups apply different rules for different operations — e.g. Create User → Password Required, Update User → Password Optional. BindingResult captures validation errors without throwing an exception — the controller can check it and return a custom response.
Common Validation Exceptions
MethodArgumentNotValidException→@RequestBody validation failed
ConstraintViolationException→@PathVariable / @RequestParam method validation failed
BindException→Form/Object binding failed
HttpMessageNotReadableException→Invalid JSON or malformed request
11. Exception Handling & ProblemDetail
Global Exception Handling handles exceptions in one place instead of every controller.
Benefits: Clean Controllers, Consistent Error Response, Reusable Logic, Easy Maintenance.
@ControllerAdvice vs @RestControllerAdvice
Global handler for Spring MVC — can return View or Response
@ControllerAdvice + @ResponseBody → returns JSON error response — preferred for REST APIs
Error Handling Flow
Client Request → Controller → Service
↓
Exception Thrown
↓
@RestControllerAdvice → @ExceptionHandler
↓
Error Response → Client
@ExceptionHandler handles a specific exception (UserNotFoundException → 404, ValidationException → 400, BusinessException → 422).
ProblemDetail (Spring Boot 3 / RFC 9457) & Standard Error Response
ProblemDetail
Standard error response introduced in Spring Boot 3, based on RFC 9457. Provides: Status, Title, Detail, Instance, Type.
Standard Error Response Fields
timestamp → Error Time, status → HTTP Status, error → Reason, message → Description, path → Request URI.
Exception → HTTP Status Mapping
| Exception | HTTP Status |
| Validation Exception | 400 |
| Entity Not Found | 404 |
| Duplicate Record | 409 |
| Business Rule Failure | 422 |
| Unexpected Exception | 500 |
12. REST Principles & Constraints
1. Client-Server→Separate UI and Backend
2. Stateless→No session stored on server
3. Cacheable→Improve performance
4. Uniform Interface→Consistent API design
5. Layered System→Client doesn't know backend architecture
6. Code On Demand (Optional)→Server can send code (JavaScript)
13. URI & Resource Design Best Practices
/users, /users/101, /orders, /orders/500/items
/getUsers, /createUser, /deleteUser, /updateUser, /saveUser, /deleteOrder
14. Safe & Idempotent Methods, PUT vs PATCH
Safe HTTP Methods
Do not modify data: GET, HEAD, OPTIONS
Idempotent Methods
Calling multiple times produces the same result: GET, PUT, DELETE, HEAD, OPTIONS
Not Idempotent: POST
PUT vs PATCH
Replace entire resource — Idempotent
Update selected fields — usually idempotent, based on implementation
15. HTTP Status Codes
| Code | Meaning | When To Use |
| 200 | OK | GET Success |
| 201 | Created | POST Success |
| 202 | Accepted | Async processing accepted |
| 204 | No Content | DELETE Success |
| 400 | Bad Request | Validation Error |
| 401 | Unauthorized | Authentication failed |
| 403 | Forbidden | Not authorized |
| 404 | Not Found | User Not Found |
| 405 | Method Not Allowed | Wrong HTTP method used |
| 409 | Conflict | Duplicate Record |
| 415 | Unsupported Media Type | Wrong Content-Type |
| 422 | Unprocessable Entity | Business validation failed |
| 500 | Internal Server Error | Unexpected server error |
| 503 | Service Unavailable | Service down / overloaded |
16. Content Negotiation — Produces & Consumes
Content Negotiation
Client chooses the desired request and response format.
Accept Header → Expected Response Format
Content-Type Header → Request Format
Content Negotiation Flow
Client → Accept: application/json
↓
Spring → Jackson
↓
JSON Response
produces → specifies response format (JSON, XML, Text). consumes → specifies accepted request format (application/json, application/xml).
17. API Versioning
Purpose: support multiple API versions without breaking clients.
URI Versioning ⭐ (Recommended)→/api/v1/users, /api/v2/users
Header Versioning→API-Version: 1
Media Type Versioning→application/vnd.company.v1+json
Query Parameter (Not Preferred)→/users?version=1
18. CORS — Cross-Origin Resource Sharing
When Is CORS Needed?
Frontend localhost:3000
↓
Backend localhost:8080 → Different Origin
↓
Browser Blocks → Enable CORS
CORS Headers
Access-Control-Allow-Origin → Allowed Domain
Access-Control-Allow-Methods → GET, POST, PUT, DELETE
Access-Control-Allow-Headers → Authorization, Content-Type
19. Idempotency
Definition: repeating the same request produces the same result.
Examples: GET /users/10 → same result. DELETE /users/10 → resource deleted; already deleted → still same state.
20. Pagination, Filtering, Sorting & Searching
Pagination→/users?page=0&size=20 — return limited data instead of the entire dataset
Filtering→/users?status=ACTIVE, /users?role=ADMIN
Sorting→/users?sortBy=name, /users?sort=createdDate,desc
Searching→/users?keyword=John, /products?name=Laptop
21. HATEOAS (Basics)
Hypermedia As The Engine Of Application State — the response contains links to related resources.
Example — User response includes: Self Link → Orders Link → Update Link.
22. REST API & Production Checklist
REST API Checklist
✓Proper URI, Proper HTTP Method, Proper Status Code
✓Validation, Exception Handling
✓Pagination, Filtering, Sorting
✓Versioning, Security, Logging, Documentation
Production API Checklist
✓RESTful URI Design, DTO Based Request/Response
✓Input Validation, Global Exception Handling
✓Pagination For Large Data, Filtering & Sorting
✓API Versioning, Secure APIs (JWT/OAuth2)
✓Correlation ID, Logging & Monitoring
✓Swagger/OpenAPI, Rate Limiting
✓Idempotency For Critical Operations, Consistent Error Response
23. Real Project Scenarios
CertifyHub GET /api/users→DispatcherServlet → UserController → UserService → UserRepository → PostgreSQL → JSON Response
Traditional ERP /home→HomeController → home.jsp
Microservice POST /payments→PaymentController → PaymentService → JSON Response
GET /api/v1/users?page=0&size=20→Pagination via @RequestParam
GET /api/v1/users?status=ACTIVE→Filtering
GET /api/v1/users?sort=username,asc→Sorting
POST /api/v1/users→201 Created
DELETE /api/v1/users/101→204 No Content
React (localhost:5173) → Spring Boot (localhost:8080)→Enable CORS
New Mobile App→API v2 while old clients continue using API v1
Duplicate Email→BusinessException → 409 Conflict
Invalid JSON→HttpMessageNotReadableException → 400 Bad Request
Authorization Header→@RequestHeader → JWT Token
CertifyHub→GlobalExceptionHandler → Consistent JSON Error Response
24. Top Interview Differences
@Controller vs @RestController
@RequestMapping vs @GetMapping
@PathVariable vs @RequestParam
PUT vs PATCH
@Valid vs @Validated
@ControllerAdvice vs @RestControllerAdvice
MethodArgumentNotValidException vs ConstraintViolationException
Safe Methods vs Idempotent Methods
Serialization vs Deserialization
@ResponseStatus vs ResponseEntity
URI Versioning vs Header Versioning vs Media Type Versioning
Produces vs Consumes
25. Interview One-Liner Revision
›Spring MVC → Web Framework
›MVC → Model View Controller
›DispatcherServlet → Front Controller
›HandlerMapping → Find Controller
›HandlerAdapter → Execute Controller
›@RestController → REST Controller
›@RequestMapping → URL Mapping
›ViewResolver → Resolve View
›HttpMessageConverter → Object ↔ JSON/XML
›REST → HTTP Based Architecture
›@GetMapping → Read Resource
›@PostMapping → Create Resource
›@PutMapping → Complete Update
›@PatchMapping → Partial Update
›@DeleteMapping → Delete Resource
›@PathVariable → URL Variable
›@RequestParam → Query Parameter
›@RequestHeader → HTTP Header
›@RequestBody → JSON To Object
›ResponseEntity → Full HTTP Response
›@ResponseStatus → Fixed Status Code
›Jackson → JSON Processor
›Serialization → Object → JSON
›Deserialization → JSON → Object
›Validation → Input Verification
›Bean Validation → Jakarta Validation API
›@Valid → Validate Object
›@Validated → Advanced Validation
›BindingResult → Validation Errors
›@ControllerAdvice → Global MVC Handler
›@RestControllerAdvice → Global REST Handler
›@ExceptionHandler → Handle Specific Exception
›ProblemDetail → Standard Error Model
›Safe Method → No Data Modification
›Idempotent → Same Result Every Time
›Content Negotiation → Response Format Selection
›Produces → Response Type
›Consumes → Request Type
›API Versioning → Multiple API Versions
›CORS → Cross-Origin Access
›Pagination → Limited Records
›Filtering → Restrict Data
›Sorting → Ordered Data
›HATEOAS → Hypermedia Links
26. 15-Minute Spring MVC & REST Revision Flow
MVC → DispatcherServlet → HandlerMapping → Controller
↓
@RestController → @RequestMapping → @GetMapping → @PostMapping
↓
@PathVariable → @RequestBody → ResponseEntity → Jackson
↓
Validation → @ControllerAdvice → REST Principles → HTTP Methods
↓
Status Codes → Content Negotiation → API Versioning
↓
CORS → Idempotency → REST Best Practices
Enterprise Best Practices
✓Keep Controllers Thin
✓Use DTOs Instead Of Entities
✓Follow REST Naming Conventions
✓Use Meaningful HTTP Status Codes
✓Validate Every Request
✓Handle Exceptions Globally
✓Return Consistent Response Structure
✓Use Pagination For Large Data Sets
✓Version Public APIs
✓Enable CORS Only For Trusted Origins
✓Make Critical APIs Idempotent
✓Document APIs Using Swagger/OpenAPI
✓Secure APIs With JWT Or OAuth2
✓Add Correlation IDs For Request Tracing
✓Monitor APIs Using Actuator & Micrometer
Interviewers Expect You To Explain
✓ Full request lifecycle through DispatcherServlet, HandlerMapping, HandlerAdapter ✓ Why REST is stateless and how that affects scaling
✓ Validation strategy — @Valid vs @Validated, and global exception handling design ✓ Correct HTTP status code for every scenario
✓ API versioning & CORS decisions made in real projects ✓ Trade-offs: PUT vs PATCH, URI vs Header versioning, ProblemDetail vs custom error DTO