Spring - Spring MVC Flashcards

1
Q

What is the role of @Controller and how is it different from @RestController in Spring MVC?

A

@Controller:
* Indicates that a class is a Spring MVC controller.
* Used in traditional web applications where handler methods return a view name (e.g., a JSP or Thymeleaf page).
* Typically used with Model or ModelAndView to pass data to the view layer.
* Requires @ResponseBody on methods if you want to return data (like JSON) directly.

@RestController:
* A convenience annotation that combines @Controller and @ResponseBody.
* Indicates that the controller is intended to return data (usually JSON or XML) instead of views.
* All methods in a class annotated with @RestController automatically return the object as the HTTP response body.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the purpose of the @RequestMapping annotation in Spring MVC?

A

The @RequestMapping annotation is used to map HTTP requests to handler methods in controller classes.

Since Spring 4.3, it’s common to use specific shortcuts like:
@GetMapping @PostMapping @PutMapping @DeleteMapping

These are more concise and clear alternatives to @RequestMapping(method = RequestMethod.GET) etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the key annotations in Spring MVC used to build a RESTful API, and what are their purposes?

A

@RestController:
A specialized version of @Controller that combines @Controller and @ResponseBody.
Indicates that the class handles REST requests and responses are written directly to the response body as JSON or XML.
@RequestMapping:
Maps HTTP requests to handler methods of REST controllers.
Can be used at the class and method level to define the base path and specific endpoints.

@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping:
Shortcut annotations for @RequestMapping(method = RequestMethod.X).
Make the code more readable and align with HTTP method semantics.

@PathVariable:
Binds a URI template variable to a method parameter.
Used for capturing values from the URI (e.g., /users/{id}).

@RequestParam:
Binds a query parameter to a method parameter (e.g., /users?active=true).

@RequestBody:
Maps the body of the HTTP request to a Java object.
Used in POST, PUT, and PATCH requests where data is sent in the request body.

@ResponseBody:
Tells Spring to serialize the return value of a method and write it directly to the HTTP response body.

@ResponseStatus:
Specifies the HTTP status code that should be returned from a method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the role of @RestControllerAdvice in a Spring MVC REST API, and how is it typically used?

A

@RestControllerAdvice is a specialized version of @ControllerAdvice combined with @ResponseBody.

Purpose and Usage:
* It is used to handle cross-cutting concerns such as global exception handling, data binding, and model attribute population across all REST controllers.
* Responses are automatically serialized (e.g., as JSON), since it behaves like @RestController.

One common usa case is Global Exception Handling:
* Define methods with @ExceptionHandler inside a class annotated with @RestControllerAdvice.
* Allows central handling of exceptions thrown by any @RestController.
* Each method can return a consistent error response structure and appropriate HTTP status.

Benefits:
* Keeps controller code clean.
* Promotes consistency and reuse in error handling logic.
* Enhances separation of concerns.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How does Spring MVC support validation of request data in a REST API?

A

Spring MVC supports validation of request data in REST APIs primarily using Java Bean Validation (JSR-380) with annotations like @Valid or @Validated.

Validation Annotations in DTOs:
Use annotations such as @NotNull, @Size, @Email, @Min, @Max, etc. directly in the request body classes (DTOs).
These constraints define the validation rules.

Triggering Validation:
Apply @Valid (or @Validated) on the method parameter annotated with @RequestBody:
public ResponseEntity<?> createUser(@Valid @RequestBody UserDTO user)
Spring will automatically validate the incoming request body against the constraints defined in the DTO.

Handling Validation Errors:
If validation fails, Spring throws a MethodArgumentNotValidException.
This can be caught globally using @ExceptionHandler in a @RestControllerAdvice class to return a meaningful error response.

Custom Validation:
You can create custom constraint annotations and validators for more complex validation logic.

Query Params and Path Variables:
For @RequestParam or @PathVariable, @Validated at the controller class level can be used with constraint annotations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How would you handle in Spring MVC Rest APIs?

A

There are several ways to handle exceptions, but best practice is @RestControllerAdvice with @ExceptionHandler.

What it is: Global exception handling. Methods annotated with @ExceptionHandler inside a class annotated with @RestControllerAdvice will handle exceptions thrown from any @RestController.

Pros:
* Centralized and reusable error handling.
* Promotes consistent error responses (e.g., standardized error JSON format).
* Cleaner controllers.

Cons:
* Slightly more setup.
* Might handle more than you intend if not scoped properly (e.g., base package filtering may be required).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly