Week 4 Day 1 — Spring MVC Mental Model: DispatcherServlet, Controllers, HandlerMapping, and REST Flow
Goal
Today I want to understand the Spring MVC request flow.
Main questions:
- What is Spring MVC?
- What problem does Spring MVC solve?
- What is
DispatcherServlet? - Why is
DispatcherServletcalled the front controller? - What is a controller?
- What is
HandlerMapping? - What is
HandlerAdapter? - What is the difference between
@Controllerand@RestController? - How does an HTTP request become a Java method call?
- How does a Java object become JSON?
- What are common exam traps?
1. Quick Review from Week 3
In Week 3, I learned:
- Spring Boot makes Spring easier to configure, run, monitor, and deploy.
@SpringBootApplicationincludes:
@Configuration
@EnableAutoConfiguration
@ComponentScan
- Starters bring dependencies.
- Auto-configuration configures beans.
- Actuator helps monitor a running application.
SpringApplication.run(...)starts the application.
Memory sentence:
Spring Boot starts the app and auto-configures common infrastructure.
Today I learn one of the most important infrastructures in web apps:
Spring MVC
2. What Is Spring MVC?
Spring MVC is the Spring Framework module for building web applications.
MVC means:
Model
View
Controller
But in modern REST APIs, we often use Spring MVC without traditional server-rendered views.
Simple definition:
Spring MVC handles HTTP requests and maps them to Java controller methods.
Example:
HTTP request:
GET /api/tasks
Java method:
@GetMapping("/api/tasks")
public List<TaskDto> getTasks() {
return taskService.findAll();
}
Spring MVC connects these two worlds.
3. What Problem Does Spring MVC Solve?
Without Spring MVC, I would need to manually handle:
HTTP routing
request parsing
query parameters
path variables
JSON request body parsing
JSON response writing
status codes
headers
validation
exception handling
content negotiation
Spring MVC gives a structured way to write web endpoints.
Instead of manually parsing low-level servlet requests, I write:
@RestController
@RequestMapping("/api/tasks")
public class TaskController {
@GetMapping
public List<TaskDto> listTasks() {
return List.of();
}
}
Memory sentence:
Spring MVC maps HTTP requests to Java methods and Java return values back to HTTP responses.
4. Spring MVC in a Spring Boot App
In Spring Boot, I usually add:
implementation("org.springframework.boot:spring-boot-starter-web")
This brings:
Spring MVC
embedded Tomcat
Jackson JSON support
web auto-configuration
HTTP message converters
Then Spring Boot auto-configures Spring MVC.
So I can write controllers without manually configuring DispatcherServlet.
5. The Big Picture Request Flow
When a request comes in:
GET /api/tasks/123
Spring MVC flow:
1. Client sends HTTP request.
2. Embedded Tomcat receives it.
3. Request goes to DispatcherServlet.
4. DispatcherServlet asks HandlerMapping: Which controller method should handle this?
5. HandlerAdapter invokes the controller method.
6. Controller calls service layer.
7. Service returns data.
8. Controller returns Java object.
9. HttpMessageConverter converts Java object to JSON.
10. DispatcherServlet sends HTTP response.
Short memory version:
Request -> DispatcherServlet -> HandlerMapping -> Controller -> Service -> JSON Response
6. What Is DispatcherServlet?
DispatcherServlet is the central servlet in Spring MVC.
It receives incoming HTTP requests and dispatches them to the correct handler.
Simple definition:
DispatcherServletis the front controller of Spring MVC.
It coordinates the request flow.
It does not contain my business logic.
It delegates to other components.
7. Why Is It Called Front Controller?
Front controller means:
One central entry point receives requests and delegates them to the correct handler.
Instead of every controller receiving raw requests directly, requests first go through:
DispatcherServlet
Mental model:
Client
↓
DispatcherServlet
↓
Correct controller method
Memory sentence:
DispatcherServletis the central entry point for Spring MVC requests.
8. What Does DispatcherServlet Do?
DispatcherServlet coordinates many things:
finds the correct handler method
invokes the handler through HandlerAdapter
handles request parameters and path variables
works with message converters
handles exceptions
selects views in traditional MVC
writes REST responses
coordinates interceptors
returns HTTP response
Important:
DispatcherServletcoordinates the flow, but it does not do everything itself.
9. What Is a Controller?
A controller is a Spring bean that handles web requests.
Example:
@RestController
@RequestMapping("/api/tasks")
public class TaskController {
@GetMapping
public List<String> getTasks() {
return List.of("Task 1", "Task 2");
}
}
This controller handles:
GET /api/tasks
Simple definition:
A controller contains methods that handle HTTP requests.
10. Controller Should Be Thin
A controller should usually be thin.
Controller responsibilities:
receive HTTP request
read request data
call service layer
return response DTO
choose status code
Controller should not contain heavy business logic.
Bad:
@RestController
public class InvoiceController {
@PostMapping("/api/invoices")
public Invoice create(@RequestBody CreateInvoiceRequest request) {
// 200 lines of tax calculation here
// database logic here
// email sending here
return invoice;
}
}
Better:
@RestController
@RequestMapping("/api/invoices")
public class InvoiceController {
private final InvoiceService invoiceService;
public InvoiceController(InvoiceService invoiceService) {
this.invoiceService = invoiceService;
}
@PostMapping
public InvoiceDto create(@RequestBody CreateInvoiceRequest request) {
return invoiceService.create(request);
}
}
Memory sentence:
Controllers handle HTTP. Services handle business logic.
11. What Is @RequestMapping?
@RequestMapping maps HTTP requests to controller classes or methods.
Class-level mapping:
@RestController
@RequestMapping("/api/tasks")
public class TaskController {
}
Method-level mapping:
@GetMapping("/{id}")
public TaskDto getTask(@PathVariable Long id) {
return taskService.findById(id);
}
Combined path:
GET /api/tasks/{id}
12. Shortcut Mapping Annotations
Instead of writing:
@RequestMapping(method = RequestMethod.GET)
Spring provides shortcuts:
@GetMapping
@PostMapping
@PutMapping
@PatchMapping
@DeleteMapping
Examples:
@GetMapping("/tasks")
@PostMapping("/tasks")
@PutMapping("/tasks/{id}")
@PatchMapping("/tasks/{id}")
@DeleteMapping("/tasks/{id}")
These match HTTP methods.
13. REST Example
@RestController
@RequestMapping("/api/tasks")
public class TaskController {
@GetMapping
public List<TaskDto> list() {
return taskService.findAll();
}
@GetMapping("/{id}")
public TaskDto get(@PathVariable Long id) {
return taskService.findById(id);
}
@PostMapping
public TaskDto create(@RequestBody CreateTaskRequest request) {
return taskService.create(request);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
taskService.delete(id);
}
}
Mappings:
GET /api/tasks -> list()
GET /api/tasks/123 -> get(123)
POST /api/tasks -> create(request)
DELETE /api/tasks/123 -> delete(123)
14. What Is HandlerMapping?
HandlerMapping finds the correct handler for a request.
Simple definition:
HandlerMappingmaps an HTTP request to a controller method.
Example request:
GET /api/tasks/123
Controller:
@GetMapping("/api/tasks/{id}")
public TaskDto getTask(@PathVariable Long id) {
}
HandlerMapping says:
This request should be handled by getTask(...)
Memory sentence:
HandlerMappinganswers: Which controller method should handle this request?
15. What Is HandlerAdapter?
HandlerAdapter invokes the selected handler method.
Simple definition:
HandlerAdapterknows how to call the controller method selected byHandlerMapping.
Why needed?
Because Spring MVC supports different kinds of handlers.
The DispatcherServlet does not directly know how to invoke every possible handler type.
So it delegates invocation to a HandlerAdapter.
Memory sentence:
HandlerMappingfinds the method.HandlerAdaptercalls the method.
16. HandlerMapping vs HandlerAdapter
| Component | Job |
|---|---|
HandlerMapping | finds the handler for the request |
HandlerAdapter | invokes the handler |
DispatcherServlet | coordinates the whole flow |
Exam memory:
Mapping finds.
Adapter invokes.
Dispatcher coordinates.
17. What Is a Handler?
In Spring MVC, a handler is usually a controller method.
Example:
@GetMapping("/api/tasks/{id}")
public TaskDto getTask(@PathVariable Long id) {
return taskService.findById(id);
}
This method is the handler for:
GET /api/tasks/{id}
So when Spring MVC says “handler,” think:
controller method
Most of the time.
18. What Is @Controller?
@Controller marks a class as a Spring MVC controller.
Example:
@Controller
public class PageController {
@GetMapping("/home")
public String home() {
return "home";
}
}
In traditional MVC, returning "home" means:
Render the view named home.
For example:
templates/home.html
19. What Is @RestController?
@RestController is used for REST APIs.
Example:
@RestController
public class TaskController {
@GetMapping("/api/tasks")
public List<String> tasks() {
return List.of("Task 1", "Task 2");
}
}
The return value is written directly to the HTTP response body.
So this Java list becomes JSON.
Memory sentence:
@RestControllerreturns data, not views.
20. @RestController = @Controller + @ResponseBody
Very important exam sentence:
@RestController = @Controller + @ResponseBody
Meaning:
@RestController
public class TaskController {
}
is conceptually similar to:
@Controller
@ResponseBody
public class TaskController {
}
@ResponseBody means:
Write the method return value directly to the HTTP response body.
21. @Controller vs @RestController
| Topic | @Controller | @RestController |
|---|---|---|
| Common use | server-rendered views | REST APIs |
| Return String | view name | response body text |
| JSON response | needs @ResponseBody | automatic |
Includes @ResponseBody | no | yes |
Example with @Controller:
@Controller
public class PageController {
@GetMapping("/home")
public String home() {
return "home";
}
}
Spring looks for a view named:
home
Example with @RestController:
@RestController
public class ApiController {
@GetMapping("/api/hello")
public String hello() {
return "hello";
}
}
Spring returns body:
hello
22. What Is @ResponseBody?
@ResponseBody tells Spring:
Do not treat the return value as a view name. Write it directly to the HTTP response body.
Example:
@Controller
public class TaskController {
@GetMapping("/api/tasks")
@ResponseBody
public List<String> tasks() {
return List.of("Task 1", "Task 2");
}
}
This returns JSON.
With @RestController, I do not need to add @ResponseBody on every method.
23. How Java Objects Become JSON
Controller:
@GetMapping("/api/tasks")
public List<TaskDto> tasks() {
return List.of(
new TaskDto(1L, "Learn Spring MVC"),
new TaskDto(2L, "Practice REST")
);
}
DTO:
public record TaskDto(Long id, String title) {
}
Response:
[
{
"id": 1,
"title": "Learn Spring MVC"
},
{
"id": 2,
"title": "Practice REST"
}
]
Who converts it?
HttpMessageConverter
Usually with Jackson for JSON.
24. What Is HttpMessageConverter?
HttpMessageConverter converts between HTTP body data and Java objects.
Two directions:
HTTP request body -> Java object
Java object -> HTTP response body
Example request:
{
"title": "Learn Spring"
}
Java object:
public record CreateTaskRequest(String title) {
}
Controller:
@PostMapping("/api/tasks")
public TaskDto create(@RequestBody CreateTaskRequest request) {
return taskService.create(request);
}
Spring uses an HttpMessageConverter to convert JSON into CreateTaskRequest.
25. Jackson and JSON
In most Spring Boot MVC apps, JSON conversion is handled by Jackson.
When I add:
implementation("org.springframework.boot:spring-boot-starter-web")
Spring Boot usually includes Jackson support.
So this works:
@RestController
public class UserController {
@GetMapping("/api/users/1")
public UserDto getUser() {
return new UserDto(1L, "Steve");
}
}
Response:
{
"id": 1,
"name": "Steve"
}
Memory sentence:
Jackson converts Java objects to JSON and JSON to Java objects.
26. What Is @RequestBody?
@RequestBody tells Spring:
Read the HTTP request body and convert it into a Java object.
Example:
POST /api/tasks
Content-Type: application/json
{
"title": "Learn Spring MVC"
}
Controller:
@PostMapping("/api/tasks")
public TaskDto create(@RequestBody CreateTaskRequest request) {
return taskService.create(request);
}
Spring converts JSON into:
CreateTaskRequest
27. What Is @PathVariable?
@PathVariable reads a value from the URL path.
Example:
GET /api/tasks/123
Controller:
@GetMapping("/api/tasks/{id}")
public TaskDto getTask(@PathVariable Long id) {
return taskService.findById(id);
}
Spring binds:
123 -> id
28. Named @PathVariable
If the variable name is different:
@GetMapping("/api/tasks/{taskId}")
public TaskDto getTask(@PathVariable("taskId") Long id) {
return taskService.findById(id);
}
Path variable:
taskId
Java parameter:
id
Spring binds taskId to id.
29. What Is @RequestParam?
@RequestParam reads query parameters.
Example:
GET /api/tasks?page=0&size=20
Controller:
@GetMapping("/api/tasks")
public List<TaskDto> listTasks(
@RequestParam int page,
@RequestParam int size
) {
return taskService.findPage(page, size);
}
Spring binds:
page=0 -> page
size=20 -> size
30. Optional @RequestParam
Example:
@GetMapping("/api/tasks")
public List<TaskDto> listTasks(
@RequestParam(required = false) String status
) {
return taskService.findByStatus(status);
}
If the query parameter is missing:
status = null
Better with default:
@GetMapping("/api/tasks")
public List<TaskDto> listTasks(
@RequestParam(defaultValue = "OPEN") String status
) {
return taskService.findByStatus(status);
}
31. @RequestBody vs @RequestParam vs @PathVariable
| Annotation | Reads from | Example |
|---|---|---|
@PathVariable | URL path | /tasks/123 |
@RequestParam | query string | /tasks?page=0 |
@RequestBody | HTTP body | JSON body |
Memory sentence:
PathVariable = path.
RequestParam = query.
RequestBody = body.
32. Full REST Flow Example
Request:
POST /api/tasks
Content-Type: application/json
{
"title": "Learn DispatcherServlet"
}
Controller:
@RestController
@RequestMapping("/api/tasks")
public class TaskController {
private final TaskService taskService;
public TaskController(TaskService taskService) {
this.taskService = taskService;
}
@PostMapping
public TaskDto create(@RequestBody CreateTaskRequest request) {
return taskService.create(request);
}
}
Request DTO:
public record CreateTaskRequest(String title) {
}
Response DTO:
public record TaskDto(Long id, String title) {
}
Flow:
1. Client sends POST /api/tasks.
2. Tomcat receives request.
3. DispatcherServlet receives request.
4. HandlerMapping finds TaskController.create().
5. HttpMessageConverter converts JSON body to CreateTaskRequest.
6. HandlerAdapter calls create(request).
7. Controller calls TaskService.
8. Service returns TaskDto.
9. HttpMessageConverter converts TaskDto to JSON.
10. DispatcherServlet sends HTTP response.
33. Returning Status Codes
By default:
@PostMapping
public TaskDto create(@RequestBody CreateTaskRequest request) {
return taskService.create(request);
}
often returns:
HTTP 200 OK
But for create operations, better:
HTTP 201 Created
Use ResponseEntity:
@PostMapping
public ResponseEntity<TaskDto> create(@RequestBody CreateTaskRequest request) {
TaskDto created = taskService.create(request);
return ResponseEntity.status(HttpStatus.CREATED).body(created);
}
34. ResponseEntity
ResponseEntity lets me control:
status code
headers
body
Example:
@GetMapping("/{id}")
public ResponseEntity<TaskDto> getTask(@PathVariable Long id) {
TaskDto task = taskService.findById(id);
return ResponseEntity.ok(task);
}
Example no content:
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteTask(@PathVariable Long id) {
taskService.delete(id);
return ResponseEntity.noContent().build();
}
Response:
HTTP 204 No Content
35. @ResponseStatus
Another way to set status:
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public TaskDto create(@RequestBody CreateTaskRequest request) {
return taskService.create(request);
}
This always returns:
201 Created
unless an exception changes the response.
Use ResponseEntity when I need more control.
Use @ResponseStatus when the status is fixed and simple.
36. Common HTTP Status Codes in REST
| Status | Meaning |
|---|---|
200 OK | successful request with response body |
201 Created | resource created |
204 No Content | successful request with no body |
400 Bad Request | invalid client request |
401 Unauthorized | authentication required or failed |
403 Forbidden | authenticated but not allowed |
404 Not Found | resource not found |
409 Conflict | conflict with current state |
500 Internal Server Error | server error |
For certification, know the common ones.
37. What Happens If No Mapping Matches?
Request:
GET /api/unknown
No controller mapping exists.
Spring MVC returns usually:
404 Not Found
Because HandlerMapping could not find a matching handler.
Memory sentence:
No matching handler usually means 404.
38. What Happens If Method Not Supported?
Controller:
@GetMapping("/api/tasks")
public List<TaskDto> list() {
return taskService.findAll();
}
Request:
POST /api/tasks
If no POST mapping exists, response is usually:
405 Method Not Allowed
Memory sentence:
Path exists but HTTP method is wrong: 405.
39. What Happens If JSON Cannot Be Parsed?
Request:
POST /api/tasks
Content-Type: application/json
{
"title":
}
Invalid JSON.
Spring cannot convert the body into Java object.
Response is usually:
400 Bad Request
Because the client sent invalid input.
40. What Happens If Type Conversion Fails?
Request:
GET /api/tasks/abc
Controller expects:
@GetMapping("/api/tasks/{id}")
public TaskDto getTask(@PathVariable Long id) {
}
Spring cannot convert:
abc -> Long
Response is usually:
400 Bad Request
41. @RequestMapping Conditions
Mappings can match based on more than path.
They can match:
path
HTTP method
request params
headers
consumes content type
produces content type
Example:
@PostMapping(
value = "/api/tasks",
consumes = "application/json",
produces = "application/json"
)
public TaskDto create(@RequestBody CreateTaskRequest request) {
return taskService.create(request);
}
Meaning:
Accept JSON request body.
Return JSON response.
42. Content Negotiation
Content negotiation means:
Spring decides what response format to produce based on request headers and available converters.
Example request header:
Accept: application/json
Spring chooses JSON if it can produce JSON.
For normal REST APIs, JSON is common.
Spring uses HttpMessageConverter for this.
Memory sentence:
Content negotiation helps choose the response format.
43. consumes and produces
consumes means:
What request content type this method accepts.
produces means:
What response content type this method returns.
Example:
@PostMapping(
value = "/api/tasks",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
public TaskDto create(@RequestBody CreateTaskRequest request) {
return taskService.create(request);
}
44. Common REST Controller Structure
@RestController
@RequestMapping("/api/tasks")
public class TaskController {
private final TaskService taskService;
public TaskController(TaskService taskService) {
this.taskService = taskService;
}
@GetMapping
public List<TaskDto> list() {
return taskService.findAll();
}
@GetMapping("/{id}")
public TaskDto get(@PathVariable Long id) {
return taskService.findById(id);
}
@PostMapping
public ResponseEntity<TaskDto> create(@RequestBody CreateTaskRequest request) {
TaskDto created = taskService.create(request);
return ResponseEntity.status(HttpStatus.CREATED).body(created);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
taskService.delete(id);
return ResponseEntity.noContent().build();
}
}
This is a clean basic REST controller.
45. DTOs vs Entities
Avoid returning JPA entities directly from controllers.
Better:
Controller returns DTOs.
Service works with domain logic.
Repository works with entities.
Bad:
@GetMapping("/api/users/{id}")
public UserEntity getUser(@PathVariable Long id) {
return userRepository.findById(id).orElseThrow();
}
Better:
@GetMapping("/api/users/{id}")
public UserDto getUser(@PathVariable Long id) {
return userService.findById(id);
}
Why?
avoid exposing internal database structure
avoid lazy loading serialization problems
control response shape
avoid leaking sensitive fields
separate API contract from persistence model
Memory sentence:
REST APIs should usually expose DTOs, not entities.
46. Spring MVC vs Spring WebFlux
Spring MVC:
servlet-based
blocking model
commonly uses Tomcat
starter: spring-boot-starter-web
Spring WebFlux:
reactive
non-blocking model
commonly uses Reactor Netty
starter: spring-boot-starter-webflux
For normal REST APIs and most certification questions:
Spring MVC + spring-boot-starter-web
Memory sentence:
Spring MVC is servlet-based. WebFlux is reactive.
47. Common Exam Traps
Trap 1
DispatcherServlet is not my controller.
It is the central front controller that dispatches requests to handlers.
Trap 2
HandlerMapping does not call the controller.
It finds the matching handler.
Trap 3
HandlerAdapter invokes the handler.
Trap 4
@RestController is @Controller plus @ResponseBody.
Trap 5
With @Controller, returning a String usually means view name.
With @RestController, returning a String means response body.
Trap 6
@RequestBody reads the HTTP body.
@RequestParam reads query parameters.
@PathVariable reads path values.
Trap 7
Java objects become JSON through HttpMessageConverter, usually Jackson.
Trap 8
No matching path usually means 404.
Wrong HTTP method usually means 405.
Bad request body or type conversion usually means 400.
Trap 9
Controllers should be thin.
Business logic belongs in services.
Trap 10
Do not expose JPA entities directly from REST APIs in most real projects.
48. Real Exam Question: Spring MVC
Question:
What is Spring MVC?
Answer:
Spring MVC is the Spring Framework module for building web applications. It maps HTTP requests to Java controller methods and helps handle request data, response data, validation, exceptions, views, and REST responses.
49. Real Exam Question: DispatcherServlet
Question:
What is DispatcherServlet?
Answer:
DispatcherServlet is the central front controller in Spring MVC. It receives incoming HTTP requests and coordinates the process of finding the correct handler, invoking it, handling the result, and returning an HTTP response.
50. Real Exam Question: HandlerMapping
Question:
What does HandlerMapping do?
Answer:
HandlerMapping finds which handler, usually a controller method, should handle a given HTTP request.
51. Real Exam Question: HandlerAdapter
Question:
What does HandlerAdapter do?
Answer:
HandlerAdapter invokes the handler method selected by HandlerMapping.
52. Real Exam Question: @Controller vs @RestController
Question:
What is the difference between @Controller and @RestController?
Answer:
@Controller is commonly used for traditional MVC controllers that return view names. @RestController is used for REST APIs and writes return values directly to the HTTP response body. @RestController is equivalent to @Controller plus @ResponseBody.
53. Real Exam Question: @ResponseBody
Question:
What does @ResponseBody do?
Answer:
@ResponseBody tells Spring to write the method return value directly to the HTTP response body instead of treating it as a view name.
54. Real Exam Question: JSON Conversion
Question:
How does Spring convert Java objects to JSON in REST controllers?
Answer:
Spring uses HttpMessageConverters. In a typical Spring Boot MVC application, Jackson is used to convert Java objects to JSON and JSON request bodies to Java objects.
55. Real Exam Question: @RequestBody
Question:
What does @RequestBody do?
Answer:
@RequestBody tells Spring to read the HTTP request body and convert it into a Java object using an HttpMessageConverter.
56. Real Exam Question: @PathVariable
Question:
What does @PathVariable do?
Answer:
@PathVariable binds a value from the URL path to a controller method parameter.
57. Real Exam Question: @RequestParam
Question:
What does @RequestParam do?
Answer:
@RequestParam binds a query parameter from the request URL to a controller method parameter.
58. Real Exam Question: ResponseEntity
Question:
Why use ResponseEntity?
Answer:
ResponseEntity allows a controller method to control the HTTP status code, response headers, and response body.
59. Real Exam Question: No Mapping
Question:
What usually happens if no controller mapping matches a request?
Answer:
Spring MVC usually returns 404 Not Found.
60. Real Exam Question: Wrong HTTP Method
Question:
What usually happens if the path exists but the HTTP method is not supported?
Answer:
Spring MVC usually returns 405 Method Not Allowed.
61. Interview Answer
Question:
Explain the Spring MVC request flow.
Good answer:
When an HTTP request comes in, the embedded servlet container receives it and forwards it to Spring MVC’s DispatcherServlet. The DispatcherServlet asks HandlerMapping to find the correct controller method. Then a HandlerAdapter invokes that method. The controller usually calls a service and returns a Java object or ResponseEntity. For REST APIs, an HttpMessageConverter, usually using Jackson, converts the Java object into JSON. Finally, DispatcherServlet sends the HTTP response back to the client.
62. Interview Answer
Question:
What is the role of
DispatcherServlet?
Good answer:
DispatcherServlet is the front controller of Spring MVC. It receives incoming HTTP requests and coordinates the request processing flow. It delegates to HandlerMapping to find the correct handler, uses a HandlerAdapter to invoke it, works with message converters and exception handlers, and returns the final HTTP response. It is the central entry point for Spring MVC requests.
63. Interview Answer
Question:
What is the difference between
@Controllerand@RestController?
Good answer:
@Controller marks a class as a Spring MVC controller, often used for traditional server-rendered views. If a method returns a String, Spring may treat it as a view name. @RestController is used for REST APIs. It includes @ResponseBody, so method return values are written directly to the HTTP response body, usually as JSON.
64. Interview Answer
Question:
How does Spring handle JSON request and response bodies?
Good answer:
Spring uses HttpMessageConverters to convert between HTTP bodies and Java objects. In a typical Spring Boot MVC application, Jackson is configured automatically by the web starter. For a request body, @RequestBody tells Spring to convert JSON into a Java object. For a response body, Spring converts the returned Java object into JSON.
65. Interview Answer
Question:
How should a REST controller be structured?
Good answer:
A REST controller should be thin. It should handle HTTP concerns such as path variables, query parameters, request bodies, status codes, and response DTOs. It should delegate business logic to a service layer. The service layer should contain business rules, and repositories should handle persistence. Controllers should usually return DTOs instead of JPA entities to keep the API contract separate from the database model.
66. Tiny Code Practice
Create a controller:
@RestController
@RequestMapping("/api/tasks")
public class TaskController {
@GetMapping("/{id}")
public TaskDto getTask(@PathVariable Long id) {
return new TaskDto(id, "Learn Spring MVC");
}
@PostMapping
public ResponseEntity<TaskDto> createTask(@RequestBody CreateTaskRequest request) {
TaskDto created = new TaskDto(1L, request.title());
return ResponseEntity.status(HttpStatus.CREATED).body(created);
}
}
DTOs:
public record TaskDto(Long id, String title) {
}
public record CreateTaskRequest(String title) {
}
Questions:
- Which method handles
GET /api/tasks/5? - Where does
idcome from? - Where does
CreateTaskRequestcome from? - What status does
createTaskreturn? - Who converts
TaskDtoto JSON?
Answers:
getTask- From the path variable
{id} - From the JSON request body via
@RequestBody 201 Created- An
HttpMessageConverter, usually using Jackson
67. Tiny Bug Practice 1
Problem:
@Controller
@RequestMapping("/api/hello")
public class HelloController {
@GetMapping
public String hello() {
return "hello";
}
}
Expected response body:
hello
But Spring tries to find a view named hello.
Question:
What is wrong?
Answer:
The class uses @Controller, so returning a String is treated as a view name unless @ResponseBody is used.
Fix option 1:
@RestController
@RequestMapping("/api/hello")
public class HelloController {
@GetMapping
public String hello() {
return "hello";
}
}
Fix option 2:
@Controller
@RequestMapping("/api/hello")
public class HelloController {
@GetMapping
@ResponseBody
public String hello() {
return "hello";
}
}
68. Tiny Bug Practice 2
Problem:
Request:
GET /api/tasks/abc
Controller:
@GetMapping("/api/tasks/{id}")
public TaskDto getTask(@PathVariable Long id) {
return taskService.findById(id);
}
Question:
What happens?
Answer:
Spring tries to convert abc to Long, but conversion fails. The response is usually 400 Bad Request.
69. Tiny Bug Practice 3
Problem:
Request:
POST /api/tasks
Content-Type: application/json
{
"title":
}
Controller:
@PostMapping("/api/tasks")
public TaskDto create(@RequestBody CreateTaskRequest request) {
return taskService.create(request);
}
Question:
What happens?
Answer:
The JSON is invalid, so Spring cannot convert the request body to CreateTaskRequest. The response is usually 400 Bad Request.
Practice Questions and Answers
Question 1
What is Spring MVC?
Answer:
Spring MVC is the Spring Framework module for building web applications. It maps HTTP requests to Java controller methods and helps handle request data, responses, validation, exceptions, views, and REST APIs.
Question 2
What problem does Spring MVC solve?
Answer:
Spring MVC solves the problem of manually handling HTTP routing, request parsing, response writing, JSON conversion, status codes, validation, and exception handling.
Question 3
What is DispatcherServlet?
Answer:
DispatcherServlet is the central front controller in Spring MVC. It receives incoming HTTP requests and coordinates request processing.
Question 4
Why is DispatcherServlet called the front controller?
Answer:
It is called the front controller because it is the central entry point for Spring MVC requests and delegates them to the correct handlers.
Question 5
What is a controller?
Answer:
A controller is a Spring bean that contains methods for handling HTTP requests.
Question 6
What does HandlerMapping do?
Answer:
HandlerMapping finds which handler, usually a controller method, should handle a request.
Question 7
What does HandlerAdapter do?
Answer:
HandlerAdapter invokes the handler selected by HandlerMapping.
Question 8
What is the difference between HandlerMapping and HandlerAdapter?
Answer:
HandlerMapping finds the handler. HandlerAdapter calls the handler.
Question 9
What is @RequestMapping?
Answer:
@RequestMapping maps HTTP requests to controller classes or methods based on path, method, headers, parameters, consumes, or produces conditions.
Question 10
Name five shortcut mapping annotations.
Answer:
Five shortcut annotations are:
@GetMapping
@PostMapping
@PutMapping
@PatchMapping
@DeleteMapping
Question 11
What is the difference between @Controller and @RestController?
Answer:
@Controller is often used for traditional MVC and can return view names. @RestController is used for REST APIs and writes return values directly to the response body. @RestController equals @Controller plus @ResponseBody.
Question 12
What does @ResponseBody do?
Answer:
@ResponseBody tells Spring to write the method return value directly to the HTTP response body instead of treating it as a view name.
Question 13
What does @RequestBody do?
Answer:
@RequestBody tells Spring to read the HTTP request body and convert it into a Java object.
Question 14
What does @PathVariable do?
Answer:
@PathVariable binds a value from the URL path to a method parameter.
Question 15
What does @RequestParam do?
Answer:
@RequestParam binds a query parameter from the URL to a method parameter.
Question 16
What is HttpMessageConverter?
Answer:
HttpMessageConverter converts between HTTP request/response bodies and Java objects.
Question 17
How does Spring usually convert Java objects to JSON?
Answer:
In a typical Spring Boot MVC app, Spring uses Jackson through an HttpMessageConverter to convert Java objects to JSON.
Question 18
What is ResponseEntity used for?
Answer:
ResponseEntity is used to control the HTTP status code, headers, and response body.
Question 19
What usually happens if no mapping matches?
Answer:
If no mapping matches, Spring MVC usually returns 404 Not Found.
Question 20
Why should controllers usually be thin?
Answer:
Controllers should usually be thin because they should handle HTTP concerns and delegate business logic to services. This keeps the code clean, testable, and maintainable.
Final Memory Sentences
- Spring MVC maps HTTP requests to Java controller methods.
DispatcherServletis the front controller of Spring MVC.DispatcherServletcoordinates the request flow.HandlerMappingfinds the handler.HandlerAdapterinvokes the handler.- A controller handles HTTP requests.
- Controllers should usually be thin.
@RestControllerequals@Controllerplus@ResponseBody.@Controllercan return view names.@RestControllerreturns response bodies.@RequestBodyreads the HTTP body.@PathVariablereads path values.@RequestParamreads query parameters.HttpMessageConverterconverts between HTTP bodies and Java objects.- Jackson usually converts Java objects to JSON.
ResponseEntitycontrols status, headers, and body.- No matching mapping usually means 404.
- Wrong HTTP method usually means 405.
- Bad request body or type conversion usually means 400.
- REST controllers should usually return DTOs, not JPA entities.