Spring MVC

0.0(0)
studied byStudied by 0 people
0.0(0)
full-widthCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/14

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

15 Terms

1
New cards

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.

2
New cards

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.

3
New cards

Difference between HandlerMapping and HandlerAdapter?

  • HandlerMapping: Finds which controller method matches the request.

  • HandlerAdapter: Actually invokes the method with correct params.

4
New cards

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).

5
New cards

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.

6
New cards

When use ResponseEntity<T>?

When you need control over status code, headers, and body. Example:

return ResponseEntity.status(HttpStatus.CREATED).body(user);

7
New cards

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

8
New cards

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).

9
New cards

Difference between @RequestParam and @PathVariable?

  • @RequestParam → query string (/users?active=true).

  • @PathVariable → URI path segment (/users/{id}).

10
New cards

What are steps to create a Rest Controller ?

  1. Annotate Class

    • Use @RestController → Marks class as REST controller.

    • Equivalent to @Controller + @ResponseBody → every handler returns response body (JSON/XML).

  2. Define Base Path

    • Use @RequestMapping("/api/...") at class level to set a common prefix for all endpoints.

  3. 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).

  4. 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.

  5. Handle Outputs

    • Return object → auto-converted to JSON by Spring (HttpMessageConverter).

    • Or wrap with ResponseEntity<T> → for custom headers/status.

  6. 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).

11
New cards

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.

12
New cards

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).

13
New cards

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.

14
New cards

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.

15
New cards

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