Week 4 Review — Spring MVC, REST APIs, Validation, and Exception Handling
Goal
This review checks if I really understand Week 4.
Week 4 topics:
- Spring MVC mental model
DispatcherServletHandlerMappingHandlerAdapter- Controllers
@Controller@RestController@RequestMapping@GetMapping,@PostMapping,@PutMapping,@PatchMapping,@DeleteMapping@PathVariable@RequestParam@RequestHeader@RequestBody@ResponseBodyHttpMessageConverter- Jackson
- DTOs
ResponseEntity- Bean Validation
@Valid@Validated- Nested validation
- Query parameter validation
- Custom validators
@ExceptionHandler@ControllerAdvice@RestControllerAdvice- Validation error handling
- HTTP error status codes
- Clean REST API design
1. Week 4 Big Picture
Week 1 answered:
How does Spring create and connect objects?
Week 2 answered:
How does Spring configure, scope, initialize, and destroy beans?
Week 3 answered:
How does Spring Boot make Spring easier to configure, run, monitor, and debug?
Week 4 answers:
How does Spring MVC receive HTTP requests, call Java controller methods, validate input, return JSON, and handle errors?
Memory sentence:
Spring MVC turns HTTP requests into Java method calls and Java return values into HTTP responses.
2. Core Spring MVC Request Flow
A request comes in:
POST /api/tasks
Content-Type: application/json
{
"title": "Learn Spring MVC"
}
Spring MVC flow:
1. Client sends HTTP request.
2. Embedded Tomcat receives it.
3. Request goes to DispatcherServlet.
4. DispatcherServlet asks HandlerMapping for the matching controller method.
5. HandlerAdapter invokes the controller method.
6. @RequestBody uses HttpMessageConverter to convert JSON to Java object.
7. Controller calls service.
8. Service returns DTO.
9. Controller returns DTO or ResponseEntity.
10. HttpMessageConverter converts Java object to JSON.
11. DispatcherServlet sends HTTP response.
Short memory version:
Request -> DispatcherServlet -> HandlerMapping -> HandlerAdapter -> Controller -> Service -> DTO -> JSON Response
3. Core Memory Sentences
Memorize these:
Spring MVC maps HTTP requests to Java controller methods.
DispatcherServlet is the front controller of Spring MVC.
DispatcherServlet coordinates request processing.
HandlerMapping finds the matching handler method.
HandlerAdapter invokes the handler method.
A controller handles HTTP requests.
Controllers should be thin.
Services should contain business logic.
@RestController equals @Controller plus @ResponseBody.
@Controller can return view names.
@RestController returns response bodies.
@RequestMapping maps requests to classes or methods.
@GetMapping maps GET requests.
@PostMapping maps POST requests.
@PutMapping maps PUT requests.
@PatchMapping maps PATCH requests.
@DeleteMapping maps DELETE requests.
@PathVariable reads values from the URL path.
@RequestParam reads query parameters.
@RequestHeader reads HTTP headers.
@RequestBody reads the HTTP request body.
@ResponseBody writes the return value to the HTTP response body.
HttpMessageConverter converts between HTTP bodies and Java objects.
Jackson usually converts Java objects to JSON and JSON to Java objects.
DTOs define the API contract.
REST APIs should usually expose DTOs, not JPA entities.
ResponseEntity controls status, headers, and body.
@Valid triggers Bean Validation.
@NotBlank is usually best for required text.
Nested DTO validation needs @Valid on the nested field.
List element validation can use List<@Valid ItemDto>.
Validation checks input shape.
Business rules belong in service or domain logic.
@ExceptionHandler handles exceptions.
@ControllerAdvice applies across controllers.
@RestControllerAdvice equals @ControllerAdvice plus @ResponseBody.
MethodArgumentNotValidException commonly happens for failed @Valid @RequestBody.
Invalid JSON usually returns 400 Bad Request.
Resource not found usually returns 404 Not Found.
Business conflict often returns 409 Conflict.
401 means authentication is missing or invalid.
403 means authenticated but not allowed.
4. Concept Map
Spring MVC / REST API
│
├── Request Flow
│ ├── DispatcherServlet
│ ├── HandlerMapping
│ ├── HandlerAdapter
│ ├── Controller
│ └── HttpMessageConverter
│
├── Controllers
│ ├── @Controller
│ ├── @RestController
│ ├── @RequestMapping
│ ├── @GetMapping
│ ├── @PostMapping
│ ├── @PutMapping
│ ├── @PatchMapping
│ └── @DeleteMapping
│
├── Request Data
│ ├── @PathVariable
│ ├── @RequestParam
│ ├── @RequestHeader
│ └── @RequestBody
│
├── Response Data
│ ├── @ResponseBody
│ ├── ResponseEntity
│ ├── DTO
│ ├── status code
│ ├── headers
│ └── body
│
├── JSON
│ ├── Jackson
│ ├── serialization
│ ├── deserialization
│ └── HttpMessageConverter
│
├── Validation
│ ├── spring-boot-starter-validation
│ ├── @Valid
│ ├── @Validated
│ ├── @NotNull
│ ├── @NotBlank
│ ├── @Size
│ ├── nested validation
│ ├── list validation
│ ├── query parameter validation
│ └── custom validators
│
└── Exception Handling
├── @ExceptionHandler
├── @ControllerAdvice
├── @RestControllerAdvice
├── @ResponseStatus
├── ResponseStatusException
├── ProblemDetail
├── MethodArgumentNotValidException
└── structured error response
5. Most Important Exam Traps
Trap 1 — DispatcherServlet
Wrong:
DispatcherServlet is my controller.
Correct:
DispatcherServlet is the central front controller. It delegates requests to the correct controller method.
Trap 2 — HandlerMapping vs HandlerAdapter
Wrong:
HandlerMapping invokes the controller.
Correct:
HandlerMapping finds the handler.
HandlerAdapter invokes the handler.
Memory:
Mapping finds.
Adapter invokes.
Dispatcher coordinates.
Trap 3 — @Controller vs @RestController
Wrong:
@Controller and @RestController are exactly the same.
Correct:
@RestController = @Controller + @ResponseBody.
With @Controller, returning "hello" can mean view name.
With @RestController, returning "hello" means response body.
Trap 4 — @RequestMapping Without HTTP Method
Wrong:
@RequestMapping("/api/tasks")
This can match multiple HTTP methods.
Better:
@GetMapping("/api/tasks")
or:
@PostMapping("/api/tasks")
Trap 5 — Class-Level and Method-Level Mapping
@RequestMapping("/api/tasks")
@GetMapping("/{id}")
means:
GET /api/tasks/{id}
Class path and method path combine.
Trap 6 — Request Data Annotations
@PathVariable = URL path
@RequestParam = query string
@RequestHeader = HTTP header
@RequestBody = HTTP body
Trap 7 — params vs @RequestParam
params chooses the method:
@GetMapping(value = "/api/tasks", params = "status")
@RequestParam reads the value:
public List<TaskDto> list(@RequestParam String status)
Memory:
params chooses.
@RequestParam reads.
Trap 8 — headers vs @RequestHeader
headers chooses the method:
@GetMapping(value = "/api/tasks", headers = "X-API-Version=2")
@RequestHeader reads the header value:
public List<TaskDto> list(@RequestHeader("X-API-Version") String version)
Trap 9 — consumes vs produces
consumes = request body format
produces = response body format
consumes checks:
Content-Type
produces relates to:
Accept
Trap 10 — @RequestBody
Wrong:
@RequestBody reads query parameters.
Correct:
@RequestBody reads the HTTP request body.
Trap 11 — One Request Body
Wrong:
public TaskDto create(
@RequestBody CreateTaskRequest request,
@RequestBody Metadata metadata
)
Correct:
public TaskDto create(@RequestBody CreateTaskCommand command)
One HTTP request has one body.
Trap 12 — Validation Needs @Valid
Wrong:
public TaskDto create(@RequestBody CreateTaskRequest request)
Correct:
public TaskDto create(@Valid @RequestBody CreateTaskRequest request)
Validation annotations need @Valid to run on request body objects.
Trap 13 — @NotNull vs @NotBlank
Wrong:
@NotNull
String title;
This allows:
""
" "
Better for required text:
@NotBlank
String title;
Trap 14 — Nested Validation
Wrong:
AddressRequest address;
Correct:
@Valid
AddressRequest address;
Nested DTO validation needs @Valid.
Trap 15 — DTO vs Entity
Wrong:
public UserEntity getUser(...)
Correct:
public UserDto getUser(...)
REST APIs should usually expose DTOs, not JPA entities.
Trap 16 — Exception Handling
Wrong:
Use try-catch in every controller method.
Correct:
Throw meaningful exceptions and handle them globally with @RestControllerAdvice.
Trap 17 — Error Details
Wrong:
Return stack traces to clients.
Correct:
Log internal details. Return safe structured error responses.
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, response data, validation, exceptions, views, and REST APIs.
Question 2
What is DispatcherServlet?
Answer:
DispatcherServlet is the central front controller in Spring MVC. It receives incoming HTTP requests and coordinates request processing.
Question 3
Why is DispatcherServlet called a front controller?
Answer:
It is called a front controller because it is the central entry point for Spring MVC requests and delegates them to the correct handlers.
Question 4
What does HandlerMapping do?
Answer:
HandlerMapping finds which handler, usually a controller method, should handle a request.
Question 5
What does HandlerAdapter do?
Answer:
HandlerAdapter invokes the handler method selected by HandlerMapping.
Question 6
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 7
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 8
What does @RequestMapping do?
Answer:
@RequestMapping maps HTTP requests to controller classes or methods. It can match by path, HTTP method, parameters, headers, consumes, and produces.
Question 9
Name five shortcut mapping annotations.
Answer:
@GetMapping
@PostMapping
@PutMapping
@PatchMapping
@DeleteMapping
Question 10
What does @PathVariable read?
Answer:
@PathVariable reads values from the URL path.
Question 11
What does @RequestParam read?
Answer:
@RequestParam reads query parameters from the URL.
Question 12
What does @RequestHeader read?
Answer:
@RequestHeader reads HTTP request headers.
Question 13
What does @RequestBody read?
Answer:
@RequestBody reads the HTTP request body and converts it into a Java object.
Question 14
What is HttpMessageConverter?
Answer:
HttpMessageConverter converts between HTTP request/response bodies and Java objects.
Question 15
What is Jackson used for?
Answer:
Jackson is usually used to serialize Java objects to JSON and deserialize JSON into Java objects.
Question 16
What is a DTO?
Answer:
A DTO, or Data Transfer Object, is an object used to transfer data across layers or API boundaries.
Question 17
Why should REST APIs usually return DTOs instead of entities?
Answer:
DTOs avoid exposing internal database structure, prevent sensitive field leaks, reduce lazy loading and infinite recursion issues, control response shape, and separate the API contract from the persistence model.
Question 18
What does ResponseEntity control?
Answer:
ResponseEntity controls HTTP status code, headers, and body.
Question 19
How do I validate a JSON request body?
Answer:
Add validation annotations to the request DTO, add spring-boot-starter-validation, and use @Valid @RequestBody in the controller method.
Question 20
What is the difference between @NotNull, @NotEmpty, and @NotBlank?
Answer:
@NotNull rejects only null. @NotEmpty rejects null and empty values. @NotBlank rejects null, empty strings, and whitespace-only strings.
Question 21
How do I validate a nested DTO?
Answer:
Put validation annotations on the nested DTO fields and put @Valid on the nested field in the parent DTO.
Question 22
What does @ExceptionHandler do?
Answer:
@ExceptionHandler marks a method that handles specific exception types thrown by controller methods.
Question 23
What does @RestControllerAdvice do?
Answer:
@RestControllerAdvice provides global exception handling across controllers and writes return values directly to the response body. It equals @ControllerAdvice plus @ResponseBody.
Question 24
What exception commonly happens when @Valid @RequestBody fails?
Answer:
MethodArgumentNotValidException.
Question 25
What is the difference between 401 and 403?
Answer:
401 Unauthorized means authentication is missing or invalid. 403 Forbidden means the user is authenticated but not allowed to perform the action.
8. Mini Mock Exam — Week 4
Instructions
Try to answer without checking notes.
Recommended time:
45 minutes
Passing score:
80%
There are 45 questions.
Question 1
What is the role of Spring MVC?
A. To map HTTP requests to Java controller methods B. To compile Java code C. To manage only database migrations D. To replace Spring Boot
My answer:
Question 2
What is DispatcherServlet?
A. The central front controller of Spring MVC B. A DTO class C. A database entity D. A validation annotation
My answer:
Question 3
What does HandlerMapping do?
A. Finds the matching handler method B. Invokes the controller method directly C. Converts JSON to Java D. Creates database tables
My answer:
Question 4
What does HandlerAdapter do?
A. Invokes the handler method B. Finds the handler mapping C. Validates database schema D. Creates HTTP clients
My answer:
Question 5
What is @RestController equivalent to?
A. @Controller + @ResponseBody
B. @Service + @Repository
C. @Entity + @Table
D. @Bean + @Autowired
My answer:
Question 6
With @Controller, returning "home" usually means:
A. View name B. JSON response always C. HTTP header D. Database table
My answer:
Question 7
With @RestController, returning "hello" means:
A. Response body text B. View name C. Bean name D. Profile name
My answer:
Question 8
What does @GetMapping map?
A. GET requests B. POST requests C. DELETE requests only D. Startup events
My answer:
Question 9
What does @PostMapping commonly represent in REST?
A. Create resource or execute command B. Read resource only C. Delete resource only D. Render template only
My answer:
Question 10
What does class-level @RequestMapping("/api/tasks") plus method-level @GetMapping("/{id}") become?
A. GET /api/tasks/{id}
B. POST /api/tasks/{id}
C. GET /{id} only
D. /api/tasks only
My answer:
Question 11
What does @PathVariable read?
A. URL path value B. Query parameter C. Request header D. Request body
My answer:
Question 12
What does @RequestParam read?
A. Query parameter B. Request body C. Response body D. Bean name
My answer:
Question 13
What does @RequestHeader read?
A. HTTP header B. Path value C. JSON body D. Database row
My answer:
Question 14
What does @RequestBody read?
A. HTTP request body B. Query parameter C. URL path D. Actuator endpoint
My answer:
Question 15
What does @ResponseBody do?
A. Writes return value to HTTP response body B. Reads query parameters C. Creates a database transaction D. Starts Tomcat
My answer:
Question 16
What is the difference between params and @RequestParam?
A. params chooses method; @RequestParam reads value
B. They are exactly the same
C. params reads JSON body
D. @RequestParam controls headers
My answer:
Question 17
What is the difference between headers and @RequestHeader?
A. headers chooses method; @RequestHeader reads value
B. They are exactly the same
C. headers reads request body
D. @RequestHeader creates beans
My answer:
Question 18
What does consumes = "application/json" mean?
A. Endpoint accepts JSON request body B. Endpoint returns HTML only C. Endpoint requires query param D. Endpoint disables validation
My answer:
Question 19
What does produces = "application/json" mean?
A. Endpoint can return JSON response B. Endpoint consumes plain text C. Endpoint requires path variable D. Endpoint creates JSON file on disk
My answer:
Question 20
Which header describes the request body format?
A. Content-Type
B. Accept
C. Authorization only
D. Location
My answer:
Question 21
Which header describes the response format the client wants?
A. Accept
B. Content-Type
C. Host only
D. Cookie only
My answer:
Question 22
What can cause 415 Unsupported Media Type?
A. Wrong request Content-Type for endpoint consumes condition
B. Missing database row
C. Wrong password only
D. Missing Java compiler
My answer:
Question 23
What can cause ambiguous mapping?
A. Two methods match the same request B. No DTOs exist C. Too many services D. Missing Actuator
My answer:
Question 24
What converts JSON to Java and Java to JSON?
A. HttpMessageConverter, usually using Jackson
B. HandlerMapping only
C. @Service
D. @Repository
My answer:
Question 25
What is Jackson?
A. JSON serialization/deserialization library B. Database server C. Web browser D. Build tool
My answer:
Question 26
What is serialization?
A. Java object to JSON B. JSON to Java object C. SQL to Java only D. HTML to CSS
My answer:
Question 27
What is deserialization?
A. JSON to Java object B. Java object to JSON C. Java to bytecode only D. Entity to table only
My answer:
Question 28
What is a DTO?
A. Data Transfer Object B. Database Transaction Object C. Docker Test Object D. Default Type Object
My answer:
Question 29
Why should REST APIs usually return DTOs instead of entities?
A. To avoid leaking internal model and sensitive fields B. Because entities cannot compile C. Because DTOs always create database tables D. Because controllers cannot return entities technically
My answer:
Question 30
What does ResponseEntity control?
A. Status, headers, and body B. Only database connection C. Only validation annotations D. Only package scanning
My answer:
Question 31
How do I return 204 No Content?
A. ResponseEntity.noContent().build()
B. ResponseEntity.ok(body)
C. return null always
D. @RequestBody
My answer:
Question 32
Which dependency is commonly needed for Bean Validation?
A. spring-boot-starter-validation
B. spring-boot-starter-css
C. spring-boot-starter-html
D. spring-boot-starter-browser
My answer:
Question 33
What triggers request body validation?
A. @Valid @RequestBody
B. Only @RequestBody
C. Only @GetMapping
D. Only @PathVariable
My answer:
Question 34
Which annotation is best for required text fields?
A. @NotBlank
B. @NotNull only
C. @Autowired
D. @Bean
My answer:
Question 35
Does @Size reject null by itself?
A. No B. Yes, always C. Only in controllers D. Only in entities
My answer:
Question 36
How do I validate nested DTOs?
A. Put @Valid on the nested field
B. Use @GetMapping
C. Use @Bean
D. Use only @PathVariable
My answer:
Question 37
How do I validate each object in a list?
A. List<@Valid ItemRequest>
B. @RequestHeader List<ItemRequest>
C. @Bean List<ItemRequest>
D. @Controller List<ItemRequest>
My answer:
Question 38
What commonly happens when @Valid @RequestBody fails?
A. MethodArgumentNotValidException
B. NullPointerException always
C. ApplicationReadyEvent
D. BeanFactory restart
My answer:
Question 39
What is @ExceptionHandler?
A. Method annotation for handling exceptions B. DTO annotation C. Database annotation D. Query parameter annotation
My answer:
Question 40
What is @RestControllerAdvice?
A. Global REST exception handling advice B. A JPA repository C. A JSON field annotation D. A package scanner only
My answer:
Question 41
What status should missing resource usually return?
A. 404 Not Found
B. 201 Created
C. 204 No Content
D. 415 Unsupported Media Type
My answer:
Question 42
What status should validation errors usually return?
A. 400 Bad Request
B. 200 OK
C. 201 Created
D. 500 always
My answer:
Question 43
What status is often used for business conflict?
A. 409 Conflict
B. 204 No Content
C. 302 Found
D. 100 Continue
My answer:
Question 44
What does 401 Unauthorized mean?
A. Authentication missing or invalid B. Authenticated but not allowed C. Resource not found D. Invalid JSON only
My answer:
Question 45
What does 403 Forbidden mean?
A. Authenticated but not allowed B. Authentication missing C. Request body is invalid JSON D. Endpoint consumes JSON
My answer:
9. Mini Mock Exam Answers
Answer Key
1. A
2. A
3. A
4. A
5. A
6. A
7. A
8. A
9. A
10. A
11. A
12. A
13. A
14. A
15. A
16. A
17. A
18. A
19. A
20. A
21. A
22. A
23. A
24. A
25. A
26. A
27. A
28. A
29. A
30. A
31. A
32. A
33. A
34. A
35. A
36. A
37. A
38. A
39. A
40. A
41. A
42. A
43. A
44. A
45. A
10. Score
Total questions: 45
Correct answers:
Wrong answers:
Score:
Score calculation:
correct answers / 45 * 100
Example:
36 / 45 * 100 = 80%
11. Mistake Review Template
For every wrong answer, write:
## Mistake
Question number:
My wrong answer:
Correct answer:
Why I was wrong:
Correct concept:
Memory sentence:
Example:
## Mistake
Question number: 16
My wrong answer: B
Correct answer: A
Why I was wrong:
I thought params and @RequestParam are the same.
Correct concept:
params is a mapping condition. @RequestParam reads the value.
Memory sentence:
params chooses. @RequestParam reads.
12. Real Scenario Questions
Scenario 1 — @Controller Returns View Name
Code:
@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?
My answer:
Model Answer
The class uses @Controller, so a returned String can be treated as a view name. For REST APIs, use @RestController or add @ResponseBody.
Correct:
@RestController
@RequestMapping("/api/hello")
public class HelloController {
@GetMapping
public String hello() {
return "hello";
}
}
Scenario 2 — Missing @RequestBody
Code:
@PostMapping("/api/tasks")
public TaskDto create(CreateTaskRequest request) {
return taskService.create(request);
}
Request:
POST /api/tasks
Content-Type: application/json
{
"title": "Learn Spring"
}
Question:
Why might JSON not bind correctly?
My answer:
Model Answer
The controller parameter is missing @RequestBody. For JSON request bodies, use:
@PostMapping("/api/tasks")
public TaskDto create(@RequestBody CreateTaskRequest request) {
return taskService.create(request);
}
Scenario 3 — Validation Does Not Run
DTO:
public record CreateTaskRequest(
@NotBlank String title
) {
}
Controller:
@PostMapping("/api/tasks")
public TaskDto create(@RequestBody CreateTaskRequest request) {
return taskService.create(request);
}
Request:
{
"title": ""
}
Validation does not run.
Question:
What is missing?
My answer:
Model Answer
@Valid is missing.
Correct:
@PostMapping("/api/tasks")
public TaskDto create(@Valid @RequestBody CreateTaskRequest request) {
return taskService.create(request);
}
Scenario 4 — Nested Validation Does Not Run
DTO:
public record CreateClientRequest(
@NotBlank String name,
AddressRequest address
) {
}
public record AddressRequest(
@NotBlank String street,
@NotBlank String city
) {
}
Question:
Why are street and city not validated?
My answer:
Model Answer
The nested field address needs @Valid.
Correct:
public record CreateClientRequest(
@NotBlank String name,
@Valid AddressRequest address
) {
}
If address is required:
public record CreateClientRequest(
@NotBlank String name,
@Valid @NotNull AddressRequest address
) {
}
Scenario 5 — Wrong Content-Type
Controller:
@PostMapping(
value = "/api/tasks",
consumes = MediaType.APPLICATION_JSON_VALUE
)
public TaskDto create(@RequestBody CreateTaskRequest request) {
return taskService.create(request);
}
Request:
POST /api/tasks
Content-Type: text/plain
hello
Question:
What status is likely?
My answer:
Model Answer
415 Unsupported Media Type, because the endpoint consumes JSON but the request sends text/plain.
Scenario 6 — Ambiguous Mapping
Code:
@GetMapping("/api/tasks")
public List<TaskDto> list1() {
return taskService.findAll();
}
@GetMapping("/api/tasks")
public List<TaskDto> list2() {
return taskService.findRecent();
}
Question:
What is wrong?
My answer:
Model Answer
Both methods match the same request: GET /api/tasks. Spring cannot decide which method to use and can fail with an ambiguous mapping error.
Scenario 7 — Returning Entity Directly
Code:
@GetMapping("/api/users/{id}")
public UserEntity getUser(@PathVariable Long id) {
return userRepository.findById(id).orElseThrow();
}
Question:
Why is this risky?
My answer:
Model Answer
Returning an entity can expose internal fields, sensitive data, lazy relationships, infinite recursion, and database structure. Return a DTO instead.
Scenario 8 — Raw Exception Exposed
Code:
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handle(Exception ex) {
return ResponseEntity.internalServerError().body(ex.toString());
}
Question:
What is wrong?
My answer:
Model Answer
It exposes raw internal exception details to the client. This can leak class names, SQL details, file paths, package names, or sensitive information. Log the exception internally and return a safe structured error response.
13. Final Oral Exam — Week 4
Try to answer these out loud.
Question 1
Explain the Spring MVC request flow.
Question 2
Explain DispatcherServlet.
Question 3
Explain HandlerMapping and HandlerAdapter.
Question 4
Explain @Controller vs @RestController.
Question 5
Explain @RequestMapping and shortcut mappings.
Question 6
Explain @PathVariable, @RequestParam, @RequestHeader, and @RequestBody.
Question 7
Explain consumes and produces.
Question 8
Explain HttpMessageConverter and Jackson.
Question 9
Explain DTOs and why APIs should not expose entities directly.
Question 10
Explain ResponseEntity.
Question 11
Explain request body validation.
Question 12
Explain nested validation.
Question 13
Explain query parameter validation.
Question 14
Explain global exception handling.
Question 15
Explain validation error handling.
14. Good Oral Answers
Oral Answer 1 — Spring MVC Request Flow
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 HandlerAdapter invokes that method. The controller usually calls a service and returns a DTO or ResponseEntity. For REST APIs, an HttpMessageConverter, usually using Jackson, converts Java objects into JSON responses.
Oral Answer 2 — DispatcherServlet
DispatcherServlet is the front controller of Spring MVC. It is the central entry point for HTTP requests. It coordinates the request flow by finding the right handler, invoking it through an adapter, handling the result, working with message converters, and returning the HTTP response.
Oral Answer 3 — HandlerMapping and HandlerAdapter
HandlerMapping finds which controller method should handle the request. HandlerAdapter invokes that controller method. In short, mapping finds and adapter invokes.
Oral Answer 4 — @Controller vs @RestController
@Controller marks a class as a Spring MVC controller, often used for server-rendered views. A returned String can be treated as a view name. @RestController is used for REST APIs. It includes @ResponseBody, so return values are written directly to the HTTP response body, usually as JSON.
Oral Answer 5 — Request Mapping
@RequestMapping maps HTTP requests to controller classes or methods. It can match by path, method, params, headers, consumes, and produces. In REST APIs, I usually use shortcut annotations such as @GetMapping, @PostMapping, @PutMapping, @PatchMapping, and @DeleteMapping.
Oral Answer 6 — Request Data Annotations
@PathVariable reads values from the URL path, such as /tasks/{id}. @RequestParam reads query parameters, such as /tasks?page=0. @RequestHeader reads HTTP headers. @RequestBody reads the HTTP request body and converts it into a Java object.
Oral Answer 7 — consumes and produces
consumes describes what request body media type the endpoint accepts, based on the Content-Type header. produces describes what response media type the endpoint can return, based on content negotiation and the Accept header.
Oral Answer 8 — HttpMessageConverter and Jackson
HttpMessageConverter converts between HTTP bodies and Java objects. For JSON in Spring Boot MVC applications, Jackson is usually used. It deserializes JSON request bodies into Java DTOs and serializes Java DTOs into JSON response bodies.
Oral Answer 9 — DTOs
A DTO is a Data Transfer Object used to define the API contract. Request DTOs describe what clients send, and response DTOs describe what the server returns. APIs should usually return DTOs instead of JPA entities to avoid exposing internal database structure, sensitive fields, lazy loading issues, and infinite recursion.
Oral Answer 10 — ResponseEntity
ResponseEntity represents the full HTTP response. It lets me control status code, headers, and body. For example, I can return 201 Created with a Location header after creating a resource, or 204 No Content after deleting a resource.
Oral Answer 11 — Request Body Validation
To validate a request body, I add validation annotations to the request DTO, such as @NotBlank, @Size, or @Email. Then I use @Valid @RequestBody in the controller method. If validation fails, Spring commonly throws MethodArgumentNotValidException and returns 400 Bad Request.
Oral Answer 12 — Nested Validation
For nested DTO validation, I put validation annotations on the nested DTO fields and add @Valid to the nested field in the parent DTO. If the nested object is required, I also add @NotNull.
Oral Answer 13 — Query Parameter Validation
To validate query parameters, I put constraints directly on method parameters, such as @RequestParam @Min(0) int page and @RequestParam @Max(100) int size. In many projects, @Validated is used on the controller class, and in modern Spring MVC method validation can also be handled by built-in support.
Oral Answer 14 — Global Exception Handling
For REST APIs, I usually use @RestControllerAdvice with @ExceptionHandler methods. This lets me map custom exceptions to HTTP status codes and structured error responses. For example, ResourceNotFoundException maps to 404, validation errors map to 400, and business conflicts map to 409.
Oral Answer 15 — Validation Error Handling
When @Valid @RequestBody fails, Spring commonly throws MethodArgumentNotValidException. I handle it globally in @RestControllerAdvice, extract field errors from the binding result, and return a structured 400 Bad Request response with field names and messages.
15. Week 4 Final Readiness Checklist
Before moving to Week 5, I should be able to check all of these:
[ ] I can explain Spring MVC.
[ ] I can explain DispatcherServlet.
[ ] I know why DispatcherServlet is the front controller.
[ ] I can explain HandlerMapping.
[ ] I can explain HandlerAdapter.
[ ] I can explain the full request flow.
[ ] I can explain @Controller.
[ ] I can explain @RestController.
[ ] I know @RestController = @Controller + @ResponseBody.
[ ] I can explain @RequestMapping.
[ ] I know @GetMapping, @PostMapping, @PutMapping, @PatchMapping, @DeleteMapping.
[ ] I can explain class-level plus method-level mappings.
[ ] I can explain @PathVariable.
[ ] I can explain @RequestParam.
[ ] I can explain @RequestHeader.
[ ] I can explain @RequestBody.
[ ] I can explain @ResponseBody.
[ ] I can explain params vs @RequestParam.
[ ] I can explain headers vs @RequestHeader.
[ ] I can explain consumes.
[ ] I can explain produces.
[ ] I know Content-Type vs Accept.
[ ] I know common mapping errors: 404, 405, 415, 406, 400.
[ ] I can explain HttpMessageConverter.
[ ] I can explain Jackson.
[ ] I know serialization and deserialization.
[ ] I can explain DTOs.
[ ] I know why DTOs are better than exposing entities.
[ ] I can explain ResponseEntity.
[ ] I can return 200, 201, 204, and 404.
[ ] I can explain Bean Validation.
[ ] I know spring-boot-starter-validation.
[ ] I can explain @Valid.
[ ] I can explain @Validated.
[ ] I know @NotNull vs @NotEmpty vs @NotBlank.
[ ] I know @Size does not reject null by itself.
[ ] I can validate request bodies.
[ ] I can validate nested DTOs.
[ ] I can validate lists.
[ ] I can validate query parameters.
[ ] I can explain custom validators.
[ ] I can explain validation vs business rules.
[ ] I can explain @ExceptionHandler.
[ ] I can explain @ControllerAdvice.
[ ] I can explain @RestControllerAdvice.
[ ] I can handle validation errors globally.
[ ] I know common error statuses: 400, 401, 403, 404, 409, 415, 500.
[ ] I know not to expose stack traces to clients.
16. Weak Topics to Review Before Week 5
Write weak topics here:
## My Weak Topics
1.
2.
3.
4.
5.
For each weak topic:
## Weak Topic
Topic:
Why it is confusing:
Correct explanation:
Code example:
Memory sentence:
17. Week 4 Final Summary
Week 4 taught me how to build REST APIs with Spring MVC.
The most important idea:
Spring MVC receives HTTP requests, calls controller methods, validates input, converts JSON, and returns HTTP responses.
The request flow is:
Request -> DispatcherServlet -> HandlerMapping -> HandlerAdapter -> Controller -> Service -> Response
For REST APIs:
@RestController returns response bodies.
@RequestBody reads JSON into DTOs.
HttpMessageConverter and Jackson convert JSON and Java objects.
ResponseEntity controls status, headers, and body.
DTOs protect the API boundary.
@Valid triggers validation.
@RestControllerAdvice handles errors globally.
If I understand Week 4 well, I am ready for Week 5:
Spring Data, Transactions, and Persistence