1/14
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
|---|
No study sessions yet.
What are the core components of Spring MVC ? and Purpose of each component ??
DispatcherServlet
Central entry point for all incoming requests.
Delegates work to other components like HandlerMapping, HandlerAdapter, and HttpMessageConverter.
HandlerMapping
Finds the right controller method based on request URL, HTTP method, and annotations (@GetMapping, @PostMapping, etc.).
Controller (@RestController / @Controller)
Contains business logic mapped to endpoints.
In REST services, typically annotated with @RestController (which combines @Controller + @ResponseBody).
HandlerAdapter
Invokes the matched controller method with the correct parameters (e.g., path variables, query params, request body).
HttpMessageConverter
Converts Java objects → JSON/XML (for responses) and JSON/XML → Java objects (for requests).
Example: MappingJackson2HttpMessageConverter handles JSON with Jackson.
Can you explain the flow of a REST request in Spring Boot?
Request Flow for REST APIs: Happy Path.
Client Request → DispatcherServlet
A request (e.g., GET /users/1) comes into the microservice.
Tomcat forwards to DispatcherServlet (auto-configured in Spring Boot).
HandlerMapping Selection
DispatcherServlet asks HandlerMapping to find the right controller method.
Mapping based on:
URL path (@RequestMapping, @GetMapping, etc.)
HTTP method (GET, POST, PUT, DELETE)
Content-Type headers
Parameters or headers conditions
Example: /users/{id} → UserController.getUserById().
HandlerAdapter Execution
Once a controller method is found, HandlerAdapter calls it.
HandlerAdapter performs critical tasks:
Resolves method parameters using ArgumentResolvers
Binds path variables (@PathVariable), request parameters (@RequestParam)
Deserializes request body using appropriate HttpMessageConverter
Validates input (@Valid annotations)
Controller Method executes Business logic:
Return Value Processing
The returned object (e.g., User) is not a view but raw data.
Because of @ResponseBody / @RestController, the object goes directly to HttpMessageConverters based on ACCEPT Header.(application/json)
HttpMessageConverter Serialization
Converts the User object → JSON (using Jackson).
Sets proper response headers (Content-Type: application/json).
Response Sent Back
DispatcherServlet writes the serialized JSON to the HTTP response.
Difference between HandlerMapping and HandlerAdapter?
HandlerMapping: Finds which controller method matches the request.
HandlerAdapter: Actually invokes the method with correct params.
How does Spring decide which HttpMessageConverter to use? What if no HttpMessageConverter is found?
Based on Content-Type (request) and Accept (response) headers. Example: JSON → MappingJackson2HttpMessageConverter.
Spring throws HttpMediaTypeNotSupportedException (for request) or HttpMediaTypeNotAcceptableException (for response).
Difference between @Controller and @RestController ??
@Controller → Marks a class as Spring MVC controller (returns views by default).
@RestController → @Controller + @ResponseBody → All methods return JSON/XML directly.
When use ResponseEntity<T>?
When you need control over status code, headers, and body. Example:
return ResponseEntity.status(HttpStatus.CREATED).body(user);What are @RequestMapping Annotation ??
@RequestMapping → Maps HTTP requests to handler methods (supports method, path, params, headers). Generic and supports all HTTP methods.
Shortcut annotations:
@GetMapping → Maps HTTP GET
@PostMapping → Maps HTTP POST
@PutMapping → Maps HTTP PUT
@DeleteMapping → Maps HTTP DELETE
@PatchMapping → Maps HTTP PATCH
What are all available annotations for Request Data binding ??
@RequestParam → Bind query parameters (/users?active=true).
@PathVariable → Bind URI path segments (/users/{id}).
@RequestHeader → Access HTTP headers.
@CookieValue → Extract cookie values.
@RequestBody → Deserialize JSON → Java object.
@ResponseBody → Serialize Java object → JSON response (implicit in @RestController).
Difference between @RequestParam and @PathVariable?
@RequestParam → query string (/users?active=true).
@PathVariable → URI path segment (/users/{id}).
What are steps to create a Rest Controller ?
Annotate Class
Use @RestController → Marks class as REST controller.
Equivalent to @Controller + @ResponseBody → every handler returns response body (JSON/XML).
Define Base Path
Use @RequestMapping("/api/...") at class level to set a common prefix for all endpoints.
Create Handler Methods
Use method-level mappings:
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping.
Optional attributes:
consumes → expected request Content-Type.
produces → response Accept type.
Return type: ResponseEntity<T> (preferred for control over body, headers, status).
Handle Inputs (with Validation)
Data Binding & Validation of inputs:
@PathVariable → extract from URI.
@RequestParam → extract from query string.
Example: /users/search?q=John&page=2&size=20.
For complex queries → use a DTO.
@RequestBody → map JSON request body → Java object.
@Valid / @Validated → apply Bean Validation rules on DTOs.
Handle Outputs
Return object → auto-converted to JSON by Spring (HttpMessageConverter).
Or wrap with ResponseEntity<T> → for custom headers/status.
Best Practices
Keep controllers thin → delegate business logic to service layer.
Return proper HTTP status codes (200 OK, 201 Created, 204 No Content, 400 Bad Request, 404 Not Found, etc.).
Use DTOs (Data Transfer Objects) instead of exposing entities directly.
Maintain consistent API design (naming, versioning, error format).
What is Data Binding ???
Spring automatically maps HTTP request data → Java objects.
Backed by:
Argument Resolvers (extract request parts).
HttpMessageConverters (e.g., Jackson for JSON).
Binding Annotations:
@PathVariable → URI path segment.
@RequestParam → Query string parameter.
@RequestBody → JSON → Java object.
Interview Tip: Spring uses Jackson ObjectMapper to convert JSON to Java and back.
Why bean validation is preferred when jackson validation is available ??
a) Jackson Validation
Jackson does basic type validation at deserialization:
If JSON sends a string for an int → error.
If a field is missing for a primitive → error (null not allowed).
❌ Limitation: Cannot validate business rules (e.g., "email must be valid", "age ≥ 18").
b) Bean Validation (Preferred)
Based on JSR-380 Bean Validation API (Hibernate Validator by default).
Allows declarative, field-level rules inside DTOs.
Favored because:
Reusable constraints (@Email, @NotBlank, @Size).
Centralized (inside DTO, not scattered across controller logic).
Framework-integrated (works with @Valid).
Extendable (custom validators possible).
How Validation error will be handled in Spring ?? What exception is thrown for invalid DTO?
If validation fails → Spring throws MethodArgumentNotValidException.
Handle globally with @ControllerAdvice.
In which layer you could do bean validation ??? and How we could ?? Is there any best pratices ??
At Controller Layer (most common) →only @valid
// Bean Validation with @Valid
@PostMapping("/users")
public ResponseEntity<UserDto> createUser(@Valid @RequestBody UserDto dto) {
return ResponseEntity.status(HttpStatus.CREATED).body(dto);
}
// Bean Validation also works with other parameter types
@GetMapping("/users/{id}")
public UserDto getUser(@Valid @PathVariable @Pattern(regexp = "\\\\d+") String id) {
// Bean validation works here too!
}
@GetMapping("/search")
public List<UserDto> searchUsers(@Valid @RequestParam @NotBlank String query) {
// And here!
}
At Service Layer (business rules)
@Valid on Methods and @validated on the class level
At Repository/DB Layer (last line of defense)
Database constraints (NOT NULL, unique indexes) → prevents invalid persistence.
👉 Best practice: Validate at controller (input) + service (business logic). DB validation only as fallback.
Difference between valid and validated.
Use @Valid for simple DTO validation in controllers (request body, path params).
Use @Validated when you need validation groups or method-level validation in service classes.
To use validation groups, I define marker interfaces, assign them to constraints in my DTO, and then trigger them with @Validated(SomeGroup.class) in controllers or services. This way I can reuse one DTO for multiple scenarios like create vs update without duplicating classes