Spring MVC Controllers Interview Questions and Answers

Master Spring MVC Controllers with interview questions covering @Controller, @RestController, @RequestMapping, request mapping annotations, path variables, request parameters, request body, ResponseEntity, DTOs, and production best practices.


Introduction

Controllers are the entry point for every Spring MVC application.

Whenever a browser, mobile application, or another microservice sends an HTTP request, it is handled by a Controller.

Examples

  • Customer Login
  • Fund Transfer
  • Order Placement
  • Product Search
  • User Registration
  • Account Statement

A controller is responsible for

  • Receiving HTTP requests
  • Validating input
  • Delegating business logic
  • Returning responses

Controllers should never contain business logic.

Their responsibility is limited to the web layer.


Controller Architecture

flowchart LR

Client --> DispatcherServlet

DispatcherServlet --> Controller

Controller --> Service

Service --> Repository

Repository --> Database

Service --> Response

Response --> Client

Q1. What is a Controller in Spring MVC?

Answer

A Controller is a Spring-managed component that processes HTTP requests.

Responsibilities

  • Receive requests
  • Extract request data
  • Validate inputs
  • Invoke service methods
  • Return responses

Example

@Controller
public class CustomerController {

}

For REST APIs, @RestController is typically used.


Q2. What is @RestController?

@RestController is a specialized controller that returns JSON or XML instead of HTML views.

It combines

  • @Controller
  • @ResponseBody

Example

@RestController
@RequestMapping("/customers")
public class CustomerController {

}

Most Spring Boot REST APIs use @RestController.


Q3. What is @RequestMapping?

@RequestMapping maps URLs to controller methods.

Example

@RequestMapping("/payments")

It can be applied

  • At class level
  • At method level

Supported HTTP methods

  • GET
  • POST
  • PUT
  • DELETE
  • PATCH

Q4. What are specialized mapping annotations?

Spring provides dedicated annotations for each HTTP method.

Annotation HTTP Method
@GetMapping GET
@PostMapping POST
@PutMapping PUT
@DeleteMapping DELETE
@PatchMapping PATCH

Example

@GetMapping("/{id}")

These improve readability over @RequestMapping.


Q5. What is @PathVariable?

@PathVariable extracts values from the URL.

Request

GET /customers/101

Example

@GetMapping("/{id}")

public Customer get(

@PathVariable Long id){

}

Result

id = 101

Q6. What is @RequestParam?

@RequestParam extracts query parameters.

Request

GET /customers?page=2

Example

@GetMapping

public List<Customer> find(

@RequestParam int page){

}

Result

page = 2

Useful for

  • Pagination
  • Filtering
  • Sorting

Q7. What is @RequestBody?

@RequestBody converts JSON into a Java object.

Request

{
  "name": "John",
  "amount": 500
}

Example

@PostMapping

public Payment create(

@RequestBody Payment payment){

}

Spring uses HttpMessageConverters for conversion.


Q8. What is ResponseEntity?

ResponseEntity provides full control over the HTTP response.

Example

return ResponseEntity
    .ok(payment);

Capabilities

  • HTTP Status
  • Headers
  • Body

Example statuses

  • 200 OK
  • 201 Created
  • 400 Bad Request
  • 404 Not Found
  • 500 Internal Server Error

Q9. Why should Controllers use DTOs?

Avoid returning JPA entities directly.

Use DTOs

  • Better security
  • Hide internal fields
  • Smaller payload
  • API versioning
  • Loose coupling

DTO Flow

flowchart LR

RequestDTO --> Controller

Controller --> Service

Service --> Entity

Entity --> ResponseDTO

ResponseDTO --> Client

Q10. Controller Best Practices

Keep Controllers Thin

Move business logic to services.


Validate Requests

Use Bean Validation annotations.


Return ResponseEntity

Provide proper HTTP status codes.


Use DTOs

Avoid exposing entities.


Implement Global Exception Handling

Use @ControllerAdvice.


Banking Example

flowchart TD

MobileApp --> PaymentController

PaymentController --> PaymentService

PaymentService --> PaymentRepository

PaymentRepository --> PostgreSQL

PaymentService --> PaymentResponseDTO

PaymentResponseDTO --> MobileApp

The controller handles HTTP communication while the service executes business logic.


Common Interview Questions

  • What is a Controller?
  • Difference between @Controller and @RestController?
  • What is @RequestMapping?
  • Explain @GetMapping, @PostMapping, @PutMapping, @DeleteMapping.
  • What is @PathVariable?
  • What is @RequestParam?
  • What is @RequestBody?
  • What is ResponseEntity?
  • Why use DTOs?
  • Controller best practices?

Quick Revision

Topic Summary
@Controller Returns views
@RestController Returns JSON/XML
@RequestMapping URL mapping
@GetMapping HTTP GET
@PostMapping HTTP POST
@PathVariable URL value
@RequestParam Query parameter
@RequestBody JSON → Java Object
ResponseEntity Full HTTP response
DTO API data transfer object

Controller Request Lifecycle

sequenceDiagram
Client->>DispatcherServlet: HTTP Request
DispatcherServlet->>Controller: Invoke Method
Controller->>Validator: Validate Input
Validator-->>Controller: Success
Controller->>Service: Business Logic
Service->>Repository: Database
Repository-->>Service: Result
Service-->>Controller: DTO
Controller->>HttpMessageConverter: Serialize JSON
HttpMessageConverter-->>Client: HTTP Response

Production Example – Banking Fund Transfer API

A banking application exposes a REST endpoint to transfer funds.

API

POST /payments

Workflow

  1. Customer submits a JSON request.

  2. @RequestBody converts JSON into PaymentRequest.

  3. Bean Validation verifies the request.

  4. PaymentController delegates to PaymentService.

  5. Service:

    • Validates balance.
    • Performs fraud checks.
    • Executes the transaction.
  6. The service returns a PaymentResponseDTO.

  7. ResponseEntity returns HTTP 201 Created.

@RestController
@RequestMapping("/payments")
public class PaymentController {

    @PostMapping
    public ResponseEntity<PaymentResponse> transfer(

            @Valid
            @RequestBody PaymentRequest request){

        PaymentResponse response =
                paymentService.transfer(request);

        return ResponseEntity
                .status(201)
                .body(response);

    }

}
flowchart LR

MobileApp --> DispatcherServlet

DispatcherServlet --> PaymentController

PaymentController --> BeanValidation

BeanValidation --> PaymentService

PaymentService --> PostgreSQL

PaymentService --> PaymentResponseDTO

PaymentResponseDTO --> ResponseEntity

ResponseEntity --> MobileApp

Benefits

  • Clean separation of concerns.
  • Strong request validation.
  • Proper HTTP status codes.
  • Secure DTO-based responses.
  • Easily testable controllers.

@Controller vs @RestController

Feature @Controller @RestController
Returns HTML View
Returns JSON With @ResponseBody ✅ Automatically
Uses ViewResolver
Uses HttpMessageConverter Optional
Best For MVC Web Applications REST APIs

Key Takeaways

  • Controllers are responsible for handling HTTP requests and delegating business logic to service classes.
  • @RestController is the preferred choice for REST APIs because it automatically serializes responses into JSON or XML.
  • @RequestMapping and its specialized variants (@GetMapping, @PostMapping, etc.) define endpoint mappings.
  • @PathVariable, @RequestParam, and @RequestBody extract data from different parts of an HTTP request.
  • ResponseEntity provides complete control over HTTP status codes, headers, and response bodies.
  • Always expose DTOs instead of JPA entities to improve security, maintainability, and API flexibility.
  • Controllers should remain thin, focusing only on request handling while business logic resides in the service layer.
  • Following these practices results in clean, maintainable, and production-ready Spring MVC applications.