Spring MVC Concepts


Spring MVC Concepts Interview with follow-up questions

1. Can you explain the MVC architecture in the context of Spring MVC?

MVC (Model–View–Controller) splits a web app into three responsibilities, and Spring MVC implements it on the servlet stack:

  1. Model — the data and business state passed between controller and view (a Model/ModelMap, or just the object you return).
  2. View — the presentation (a Thymeleaf/JSP template rendering HTML) — or, for an API, no view: the return value is serialized to JSON.
  3. Controller — your @Controller/@RestController handler methods: receive the request, invoke business logic, and return data + a view name (or a response body).

The piece that ties it together is the front controller, DispatcherServlet: it receives every request, uses HandlerMapping to find the controller, invokes it, and uses a ViewResolver to render the result.

@RestController
class ProductController {
  @GetMapping("/products/{id}")
  Product get(@PathVariable Long id) { return service.find(id); }  // body → JSON
}

The 2026 framing interviewers want: most apps today build REST APIs (@RestController + JSON via Jackson), so the classic View layer is mainly for server-rendered pages. The MVC benefit is separation of concerns — testable controllers, swappable views — and it now runs even more efficiently with virtual threads, while WebFlux is the reactive alternative.

↑ Back to top

Follow-up 1

How does the DispatcherServlet work in Spring MVC?

The DispatcherServlet is the front controller in the Spring MVC framework. It receives all incoming requests and delegates them to the appropriate controllers for processing. Here is how the DispatcherServlet works:

  1. When a request is received, the DispatcherServlet is invoked.

  2. The DispatcherServlet consults the HandlerMapping to determine the appropriate controller for the request.

  3. The selected controller is invoked to process the request. It performs the necessary business logic and updates the Model.

  4. The controller returns a ModelAndView object, which contains the name of the View to render and any model data.

  5. The DispatcherServlet consults the ViewResolver to find the appropriate View based on the name returned by the controller.

  6. The selected View is rendered with the model data, and the resulting response is sent back to the client.

The DispatcherServlet acts as a central hub for request handling in Spring MVC, coordinating the flow of requests and responses between the various components of the MVC architecture.

Follow-up 2

What is the role of the WebApplicationContext in Spring MVC?

The WebApplicationContext is a specialized ApplicationContext implementation provided by Spring MVC for web applications. It plays a crucial role in the configuration and initialization of Spring MVC components. Here are some key roles of the WebApplicationContext:

  1. It provides a way to configure and manage the lifecycle of web-specific beans, such as controllers, view resolvers, and interceptors.

  2. It supports the use of annotations, such as @Controller and @RequestMapping, to define the web components and their mappings.

  3. It integrates with the Servlet API to provide access to web-related features, such as request and session attributes.

  4. It allows for the configuration of web-specific features, such as multipart file uploading, internationalization, and theme support.

Overall, the WebApplicationContext is responsible for managing the web-specific components and providing the necessary infrastructure for Spring MVC to handle web requests and responses.

Follow-up 3

Can you explain the concept of ViewResolver in Spring MVC?

In Spring MVC, a ViewResolver is responsible for resolving the logical view names returned by the controllers into actual View objects that can render the response. It allows for the decoupling of the controller logic from the actual rendering of the response. Here is how the ViewResolver works:

  1. When a controller returns a logical view name, such as "home" or "product", the ViewResolver is invoked.

  2. The ViewResolver consults its configured set of View implementations to find the appropriate View for the given logical view name.

  3. Once the View is resolved, it is used to render the response. The View can be a JSP, a Thymeleaf template, a FreeMarker template, or any other type of view technology.

  4. The View is responsible for rendering the model data provided by the controller and generating the final response.

The ViewResolver provides flexibility in choosing different view technologies and allows for easy switching between them without changing the controller logic.

2. How does data binding work in Spring MVC?

Data binding maps incoming request data (query/form params, path variables, request body) onto Java objects, so you work with typed objects instead of parsing raw strings. Spring's WebDataBinder and HttpMessageConverters do the work.

The mechanisms you'll actually use:

  • @RequestBody — deserialize a JSON body into an object (Jackson) — the norm for REST APIs.
  • @ModelAttribute — bind form/query params onto a command object (server-rendered forms).
  • @RequestParam — bind a single query/form parameter; @PathVariable — bind a URI template variable.
  • Type conversion — Spring's Converter/Formatter (the modern replacement for legacy PropertyEditors) handle string→type conversion (dates, enums, numbers).
@PostMapping("/users")
User create(@Valid @RequestBody UserDto dto) { ... }   // JSON → object + validation

The points interviewers reward: pair binding with @Valid/@Validated (Jakarta Bean Validation) to validate the bound object, and capture errors with a BindingResult; customize/limit binding with @InitBinder (and restrict fields to avoid mass-assignment vulnerabilities). For 2026, note the legacy PropertyEditor approach has been superseded by the Converter/Formatter SPI, and REST APIs bind via JSON converters rather than form command objects.

↑ Back to top

Follow-up 1

What is the role of the @ModelAttribute annotation in data binding?

The @ModelAttribute annotation in Spring MVC is used to bind a method parameter or a method return value to a named model attribute. When used on a method parameter, it indicates that the parameter should be bound to a model attribute with the same name. When used on a method return value, it indicates that the return value should be added to the model with the specified name.

In the context of data binding, the @ModelAttribute annotation can be used to automatically bind the request parameters to the model attributes. For example, if you have a method with a @ModelAttribute parameter, Spring MVC will automatically bind the request parameters to the corresponding fields of the model attribute.

Follow-up 2

How can you handle data binding errors in Spring MVC?

In Spring MVC, you can handle data binding errors by using the BindingResult interface. The BindingResult interface is used to store and retrieve the binding errors that occur during the data binding process.

To handle data binding errors, you can perform the following steps:

  1. Add a BindingResult parameter to your controller method along with the model attribute parameter.

  2. Use the BindingResult.hasErrors() method to check if there are any binding errors.

  3. If there are binding errors, you can retrieve the error messages using the BindingResult.getFieldErrors() method.

  4. You can then display the error messages to the user or perform any other error handling logic.

By using the BindingResult interface, you can easily handle data binding errors and provide meaningful feedback to the user.

Follow-up 3

Can you explain the concept of Form Backing Objects in Spring MVC?

In Spring MVC, Form Backing Objects are used to represent the form data submitted by the user. They are Java objects that encapsulate the form data and provide a convenient way to bind the form data to the model attributes.

Form Backing Objects are typically used in conjunction with the @ModelAttribute annotation. When a form is submitted, Spring MVC automatically binds the form data to the Form Backing Object using the @ModelAttribute annotation.

Form Backing Objects can also be used to perform validation on the form data. Spring MVC provides various validation annotations that can be used to validate the Form Backing Objects.

Overall, Form Backing Objects simplify the process of handling form submissions in Spring MVC by encapsulating the form data and providing a convenient way to bind the data to the model attributes.

3. How does Spring MVC handle exceptions?

Spring MVC offers layered exception handling, from local to global:

  • @ExceptionHandler — a method in a controller that handles specific exceptions for that controller.
  • @ControllerAdvice / @RestControllerAdvice — a global handler applying across all controllers; the standard place to centralize error handling for an API.
  • @ResponseStatus — annotate an exception (or handler) to map it to an HTTP status.
  • HandlerExceptionResolver — the low-level SPI Spring uses internally if you need full control.

The modern, recommended approach for REST APIs is a @RestControllerAdvice returning RFC 9457 ProblemDetail (built into Spring 6) — often by extending ResponseEntityExceptionHandler:

@RestControllerAdvice
class ApiExceptionHandler {
  @ExceptionHandler(NotFoundException.class)
  ProblemDetail handle(NotFoundException ex) {
    return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
  }
}

Points worth adding: this gives consistent, structured error responses without leaking stack traces; Boot also provides a default error response (/error, customizable via ErrorAttributes). The 2026 detail that signals current knowledge is using ProblemDetail as the standard error payload rather than ad-hoc JSON.

↑ Back to top

Follow-up 1

What is the role of the @ExceptionHandler annotation?

The @ExceptionHandler annotation is used to handle exceptions within a specific controller. By annotating a method with @ExceptionHandler and specifying the exception type as a parameter, Spring MVC will invoke that method when the specified exception occurs within the controller. The method can then handle the exception and return a response to the client.

Follow-up 2

Can you explain the difference between @ExceptionHandler and @ControllerAdvice?

The @ExceptionHandler annotation is used to handle exceptions within a specific controller, while the @ControllerAdvice annotation is used to handle exceptions globally across multiple controllers. When an exception occurs within a controller, Spring MVC will first check for an @ExceptionHandler method within that controller to handle the exception. If no matching @ExceptionHandler method is found, Spring MVC will then check for an @ExceptionHandler method within any controller advice annotated with @ControllerAdvice.

Follow-up 3

How can you handle global exceptions in Spring MVC?

To handle global exceptions in Spring MVC, you can use the @ControllerAdvice annotation. By annotating a class with @ControllerAdvice, you can define methods that handle exceptions across multiple controllers. These methods can be annotated with @ExceptionHandler to specify the exception types they handle. When an exception occurs within any of the controllers, Spring MVC will check for a matching @ExceptionHandler method within the controller advice and invoke it to handle the exception.

4. What are some of the key components of Spring MVC?

The core components of Spring MVC's request-handling pipeline:

  • DispatcherServlet — the front controller; single entry point that orchestrates everything.
  • HandlerMapping — maps a request (URL + HTTP method) to the handler method (RequestMappingHandlerMapping for @RequestMapping/@GetMapping).
  • HandlerAdapter — invokes the matched handler, resolving its arguments.
  • Controller — your @Controller/@RestController with handler methods.
  • HttpMessageConverter — serializes/deserializes request and response bodies (Jackson for JSON) — central to REST.
  • ViewResolver + View — resolve a logical view name to a template and render it (server-rendered apps).
  • HandlerInterceptor — pre/post hooks (auth, logging) around handlers.
  • HandlerExceptionResolver — turns exceptions into responses.
Request → DispatcherServlet → HandlerMapping → HandlerAdapter → Controller
        → (JSON via HttpMessageConverter) or (ViewResolver → View) → Response

The framing interviewers want: the DispatcherServlet coordinates the rest, and for REST APIs the HttpMessageConverter (JSON) replaces the ViewResolver/View path. Model carries data to the view in server-rendered apps. Mentioning interceptors, message converters, and ProblemDetail-based exception resolvers shows current, REST-oriented understanding.

↑ Back to top

Follow-up 1

Can you explain the role of the Controller in Spring MVC?

The Controller in Spring MVC is responsible for handling the incoming requests and returning the appropriate response. It receives the requests from the DispatcherServlet and processes them by invoking the appropriate methods. The Controller is responsible for fetching the data from the Model, performing any necessary business logic, and returning the response to the user.

Follow-up 2

What is the purpose of the ModelAndView object?

The ModelAndView object in Spring MVC is used to pass data between the Controller and the View. It allows the Controller to set the data that needs to be rendered by the View, as well as any additional information such as the view name or any model attributes. The ModelAndView object is returned by the Controller's handler methods and is then used by the ViewResolver to render the response.

Follow-up 3

How does the RequestMapping annotation work?

The RequestMapping annotation in Spring MVC is used to map the incoming requests to the appropriate handler methods in the Controller. It can be applied at the class level to specify a common base URL for all the handler methods in the Controller, and at the method level to specify the specific URL pattern that should be mapped to the method. The RequestMapping annotation supports various attributes such as method, params, headers, and consumes/produces to further refine the mapping criteria.

5. Can you explain the process of request processing in Spring MVC?

The request flow through Spring MVC:

  1. Request arrives at the DispatcherServlet (front controller).
  2. It asks HandlerMapping which handler matches the URL + HTTP method.
  3. A HandlerAdapter invokes the controller method, binding arguments (@PathVariable, @RequestParam, @RequestBody via message converters) and running validation; registered HandlerInterceptors fire before/after.
  4. The controller executes business logic and returns either:
    • a response body (@ResponseBody/@RestController) → serialized to JSON by an HttpMessageConverter, or
    • a logical view name (@Controller) → resolved by a ViewResolver and rendered with the model.
  5. If anything throws, a HandlerExceptionResolver (e.g. @ControllerAdvice) produces the error response.
  6. The DispatcherServlet writes the response back to the client.
Client → DispatcherServlet → HandlerMapping → HandlerAdapter → Controller
       → [JSON converter] / [ViewResolver → View] → Response

The 2026 nuance: for the REST case (most apps), step 4 is the message-converter/JSON path, not view resolution — the old ModelAndView→view flow is mainly for server-rendered pages. The whole pipeline is single request-per-thread (now cheaply scalable with virtual threads), with WebFlux as the non-blocking alternative.

↑ Back to top

Follow-up 1

What is the role of the HandlerMapping in request processing?

The HandlerMapping in Spring MVC is responsible for mapping a request to an appropriate controller. It determines which controller should handle the request based on the request URL or other criteria. The HandlerMapping is configured in the Spring application context and can be customized to use different strategies for mapping requests to controllers.

Follow-up 2

How does the Controller process the request?

The Controller in Spring MVC processes the request by receiving the request parameters and any other necessary data from the client. It then performs the required business logic or delegates the processing to other components such as services or repositories. After processing the request, the Controller typically returns a ModelAndView object, which contains the data to be displayed and the view name to be rendered.

Follow-up 3

What happens after the Controller processes the request?

After the Controller processes the request and returns a ModelAndView object, the DispatcherServlet takes over. The DispatcherServlet consults the ViewResolver to determine the appropriate view for the response. The ViewResolver resolves the view name to an actual view implementation, which is responsible for rendering the response. The rendered response is then sent back to the DispatcherServlet, which sends it back to the client.

6. How do you call other services from Spring — RestClient vs WebClient vs RestTemplate?

Spring offers three HTTP clients; knowing which is current matters:

  • RestTemplate — the classic synchronous client. Still supported but in maintenance mode (no new features) — avoid for new code.
  • RestClient (Spring 6.1+) — the modern synchronous client with a fluent, RestTemplate-replacing API. The recommended default for blocking/MVC apps.
  • WebClient — the reactive, non-blocking client (Project Reactor). Use it in WebFlux apps, or when you want async/streaming/backpressure even in an MVC app.
RestClient client = RestClient.create();
User u = client.get().uri("/users/{id}", id).retrieve().body(User.class);

Also worth naming: HTTP Interfaces (@HttpExchange) — declare a Java interface and let Spring generate the client implementation (backed by RestClient or WebClient), much like Feign; Spring Framework 7 / Boot 4 enhanced this with a registry so client proxies are auto-registered as beans.

The framing interviewers want: "RestClient for sync, WebClient for reactive — RestTemplate is legacy, and prefer declarative @HttpExchange interfaces for clean, type-safe clients."

↑ Back to top

Live mock interview

Mock interview: Spring MVC Concepts

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.