Spring Web MVC


Spring Web MVC Interview with follow-up questions

1. What is Spring Web MVC and how does it work?

Spring Web MVC is Spring's servlet-based web framework for building web apps and REST APIs, structured around the MVC pattern and driven by the front-controller DispatcherServlet.

How it works:

  1. The DispatcherServlet receives every request.
  2. HandlerMapping finds the matching @Controller/@RestController method.
  3. A HandlerAdapter invokes it, binding path variables/params/body and validating.
  4. The controller returns data — serialized to JSON via an HttpMessageConverter for APIs, or a logical view name resolved by a ViewResolver for server-rendered pages.
  5. The DispatcherServlet writes the response.
@RestController
@RequestMapping("/api/users")
class UserController {
  @GetMapping("/{id}") User get(@PathVariable Long id) { ... }
  @PostMapping User create(@Valid @RequestBody UserDto dto) { ... }
}

The 2026 framing: in Spring Boot, spring-boot-starter-web auto-configures all of this (and embeds Tomcat), so you just write controllers. It runs on the blocking servlet stack — now cheap to scale per-request with Java virtual threads — while Spring WebFlux is the separate reactive, non-blocking option for high-concurrency/streaming needs. Most teams still choose MVC for typical request/response APIs.

↑ Back to top

Follow-up 1

Can you explain the DispatcherServlet in Spring MVC?

The DispatcherServlet is the front controller in Spring MVC. It receives all the requests made to a Spring MVC application and delegates them to the appropriate controller for processing. The DispatcherServlet is responsible for managing the entire request-response lifecycle.

When a request is made, the DispatcherServlet first consults the HandlerMapping to determine which controller should handle the request. Once the controller is determined, the DispatcherServlet invokes the controller's methods to process the request. After the controller has finished processing the request, it returns a logical view name.

The DispatcherServlet then consults the ViewResolver to resolve the logical view name to an actual view. The view is responsible for rendering the response. Finally, the DispatcherServlet sends the response back to the client.

Follow-up 2

How does the Spring MVC handle requests?

Spring MVC handles requests by following the Model-View-Controller (MVC) architectural pattern. When a request is made to a Spring MVC application, it is first received by the DispatcherServlet, which acts as the front controller. The DispatcherServlet consults the HandlerMapping to determine the appropriate controller for the request.

Once the controller is determined, the DispatcherServlet invokes the controller's methods to process the request. The controller updates the model and returns a logical view name.

The DispatcherServlet then consults the ViewResolver to resolve the logical view name to an actual view. The view is responsible for rendering the response. Finally, the DispatcherServlet sends the response back to the client.

Follow-up 3

What is the role of a ViewResolver in Spring MVC?

A ViewResolver in Spring MVC is responsible for resolving the logical view name returned by a controller to an actual view. It determines which view should be used to render the response.

The ViewResolver is configured in the Spring MVC application context and can be customized to support different view technologies such as JSP, Thymeleaf, or FreeMarker.

When the DispatcherServlet receives a logical view name from a controller, it consults the ViewResolver to find the appropriate view. The ViewResolver returns the view, which is then used to render the response. If the logical view name is not found by any ViewResolver, an exception is thrown.

2. What are the benefits of using Spring Web MVC?

Benefits of Spring Web MVC:

  1. Clean separation of concerns — the MVC structure keeps request handling, business logic, and presentation/serialization distinct, which aids maintainability and testing.
  2. Annotation-driven and concise@RestController, @GetMapping, @RequestBody, etc. make endpoints declarative; auto-configured by Spring Boot.
  3. Highly testableMockMvc/MockMvcTester and @WebMvcTest let you test controllers without a running server.
  4. Powerful binding & validation — automatic data binding plus Jakarta Bean Validation (@Valid) and structured ProblemDetail error responses.
  5. Flexible & extensible — interceptors, message converters, content negotiation, and pluggable view technologies.
  6. Deep ecosystem integration — works seamlessly with Spring Security, Spring Data, Actuator, and observability.
  7. Mature, stable, well-documented — the default choice for Java web/REST development.

The current framing: a major 2026 advantage is that the blocking MVC model now scales cheaply with Java virtual threads (spring.threads.virtual.enabled=true) — you keep the simple imperative programming model and still handle high concurrency, which for many teams removes the main reason they'd have reached for reactive WebFlux.

↑ Back to top

Follow-up 1

How does Spring MVC support RESTful services?

Spring MVC provides support for building RESTful services through the use of the @RestController annotation and the @RequestMapping annotation with the appropriate HTTP methods (e.g., @GetMapping, @PostMapping, etc.).

By annotating a controller class with @RestController, Spring MVC automatically serializes the return value of the controller methods into JSON or XML, depending on the request's Accept header.

Additionally, Spring MVC provides support for content negotiation, allowing clients to specify the desired representation format (e.g., JSON, XML) through the Accept header or query parameters.

Spring MVC also supports the use of the @PathVariable annotation to extract path variables from the request URI, and the @RequestBody annotation to bind request body data to method parameters.

Follow-up 2

Can you compare Spring MVC with other Java web frameworks?

Spring MVC is one of the most popular Java web frameworks, but there are other frameworks available as well. Here are some comparisons between Spring MVC and other Java web frameworks:

  1. Spring MVC vs. JavaServer Faces (JSF): Spring MVC follows the Model-View-Controller (MVC) architectural pattern, while JSF follows the Component-Based Model-View-Controller (C-MVC) pattern. Spring MVC provides more flexibility and control over the application flow, while JSF simplifies the development of user interfaces through the use of reusable UI components.

  2. Spring MVC vs. Struts: Spring MVC and Struts both follow the MVC pattern, but Spring MVC provides more flexibility and extensibility compared to Struts. Spring MVC also has better integration with other Spring modules.

  3. Spring MVC vs. Play Framework: Spring MVC is a traditional server-side web framework, while Play Framework is a modern reactive web framework. Play Framework is more suitable for building highly scalable and reactive applications.

Follow-up 3

How does Spring MVC handle form submissions?

Spring MVC provides several ways to handle form submissions:

  1. Model binding: Spring MVC can automatically bind form data to Java objects using the @ModelAttribute annotation. This allows you to define a form backing object that represents the form data, and Spring MVC will automatically populate the object with the submitted data.

  2. Validation: Spring MVC supports validation of form data using the @Valid annotation and the javax.validation API. You can annotate the form backing object with validation constraints, and Spring MVC will automatically validate the submitted data.

  3. Form tags: Spring MVC provides form tags that can be used in JSP or Thymeleaf templates to generate HTML forms. These tags handle the rendering of form fields, as well as the binding and validation of form data.

  4. Redirect-after-post: Spring MVC supports the redirect-after-post pattern, which helps prevent duplicate form submissions. After processing a form submission, Spring MVC can redirect the user to another URL, preventing the user from accidentally resubmitting the form by refreshing the page.

3. How does Spring MVC handle exception handling?

Spring MVC provides several layered options:

  1. @ExceptionHandler — handle specific exceptions within a single controller; the method can return a ResponseEntity, a body, or a view.
  2. @RestControllerAdvice / @ControllerAdvice — a global handler across all controllers; the standard place to centralize API error handling.
  3. @ResponseStatus — map an exception type directly to an HTTP status code.
  4. HandlerExceptionResolver — the low-level SPI for full control (the legacy SimpleMappingExceptionResolver mapped exceptions to error views — mostly relevant only for old server-rendered apps).

The modern best practice for REST is a @RestControllerAdvice returning ProblemDetail (RFC 9457, built into Spring 6), optionally by extending ResponseEntityExceptionHandler:

@RestControllerAdvice
class ApiErrors {
  @ExceptionHandler(IllegalArgumentException.class)
  ProblemDetail badRequest(IllegalArgumentException ex) {
    return ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, ex.getMessage());
  }
}

Points interviewers reward: this yields consistent, structured error payloads without leaking internals; Spring Boot adds a default /error response you can customize via ErrorAttributes. Using ProblemDetail (rather than SimpleMappingExceptionResolver or ad-hoc JSON) is the up-to-date answer.

↑ Back to top

Follow-up 1

What is the @ExceptionHandler annotation?

The @ExceptionHandler annotation is used in Spring MVC to handle specific exceptions within a controller. You can define methods annotated with @ExceptionHandler that will be invoked when the specified exception occurs. These methods can return a ResponseEntity or a ModelAndView to handle the exception. The @ExceptionHandler annotation can be used at the method level within a controller or at the class level within a @ControllerAdvice class to handle exceptions across multiple controllers.

Follow-up 2

How can you define a global exception handler in Spring MVC?

You can define a global exception handler in Spring MVC using the @ControllerAdvice annotation. By annotating a class with @ControllerAdvice, you can define methods that will be invoked to handle exceptions across multiple controllers. These methods can be annotated with @ExceptionHandler to handle specific exceptions or with @ResponseStatus to define the HTTP status code that should be returned when the exception occurs. The @ControllerAdvice class can also include other annotations such as @InitBinder and @ModelAttribute to provide additional functionality.

Follow-up 3

What is the difference between @ControllerAdvice and @ExceptionHandler?

The @ControllerAdvice annotation is used to define a global exception handler in Spring MVC. It allows you to handle exceptions across multiple controllers. On the other hand, the @ExceptionHandler annotation is used to handle specific exceptions within a controller. It allows you to define methods that will be invoked when the specified exception occurs. While @ControllerAdvice is used at the class level to define a global exception handler, @ExceptionHandler is used at the method level within a controller to handle specific exceptions.

4. Can you explain the concept of data binding in Spring MVC?

Data binding is Spring MVC's automatic mapping of request data → typed Java objects, so handlers receive ready-to-use objects instead of raw strings. The relevant annotations:

  • @RequestBody — deserialize a JSON body into an object (Jackson) — standard for REST APIs.
  • @ModelAttribute — bind form/query parameters onto a command object (server-rendered forms).
  • @RequestParam — bind a single query/form parameter (with required/defaultValue).
  • @PathVariable — bind a URI template segment (/users/{id}).
  • @RequestHeader / @CookieValue — bind headers/cookies.
@GetMapping("/search")
List search(@RequestParam String q,
                  @RequestParam(defaultValue = "10") int size) { ... }

Behind the scenes, Converter/Formatter components handle type conversion (strings → dates, enums, numbers — the modern replacement for legacy PropertyEditors), and HttpMessageConverters handle body (de)serialization. Pair binding with @Valid (Bean Validation) and a BindingResult to validate input, and restrict bound fields (@InitBinder/DTOs) to avoid mass-assignment issues. The takeaway: binding removes boilerplate parsing and is where validation hooks in.

↑ Back to top

Follow-up 1

What is the role of @ModelAttribute annotation?

The @ModelAttribute annotation is used to bind a method parameter or method return value to a named model attribute. When used on a method parameter, it indicates that the parameter should be retrieved from the model or the request's parameters. When used on a method return value, it indicates that the value should be added to the model and made available to the view. The @ModelAttribute annotation can also be used to specify the name of the model attribute.

Follow-up 2

How does Spring MVC convert form data to a Java object?

Spring MVC uses the concept of data binding to convert form data to a Java object. When a form is submitted, Spring MVC automatically maps the form fields to the properties of a Java object. This is done by matching the names of the form fields with the names of the properties in the Java object. Spring MVC uses the JavaBean convention to set the values of the properties. If the form data contains nested objects or collections, Spring MVC can also handle the conversion automatically.

Follow-up 3

What is a BindingResult object in Spring MVC?

A BindingResult object is used to hold the results of data binding and validation in Spring MVC. It represents the outcome of the data binding process and contains any errors or validation messages that occurred during the process. The BindingResult object is typically used in conjunction with the @Valid annotation to perform validation on the model object. It allows you to check for errors and retrieve error messages in the controller or in the view.

5. How does Spring MVC handle file uploads?

Spring MVC handles file uploads via multipart requests, binding the uploaded file to a MultipartFile (or jakarta.servlet.http.Part). In Spring Boot the multipart resolver is auto-configured, so you just declare the parameter:

@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
ResponseEntity upload(@RequestParam("file") MultipartFile file) throws IOException {
  String name = file.getOriginalFilename();
  file.transferTo(Path.of("/data/uploads", sanitize(name)));   // save it
  return ResponseEntity.ok("uploaded");
}
// multiple files: @RequestParam List files

MultipartFile gives you getOriginalFilename(), getContentType(), getSize(), getBytes(), getInputStream(), and transferTo(...).

Points interviewers reward: configure size limits (spring.servlet.multipart.max-file-size / max-request-size) to prevent abuse/DoS; never trust getOriginalFilename() — sanitize it to avoid path traversal, and validate content type/extension; for large files stream rather than loading bytes into memory; and consider offloading to object storage (S3) instead of local disk. A current note: the underlying API is now jakarta.servlet (not javax.servlet) since Spring 6 / Boot 3.

↑ Back to top

Follow-up 1

What is MultipartResolver and when is it used?

MultipartResolver is an interface in Spring MVC that resolves multipart requests. It is used to handle file uploads in Spring MVC. MultipartResolver implementations are responsible for parsing the multipart request and providing access to the uploaded files.

Follow-up 2

How can you handle multiple file uploads in Spring MVC?

To handle multiple file uploads in Spring MVC, you can use an array or a List of MultipartFile objects as a method parameter in your controller method. Spring MVC will automatically bind the uploaded files to the array or List.

Follow-up 3

What are the limitations of file upload in Spring MVC?

There are a few limitations of file upload in Spring MVC:

  1. File size limit: By default, Spring MVC limits the maximum file size to 1MB. This can be configured using the 'spring.servlet.multipart.max-file-size' property in the application.properties file.

  2. File type restrictions: Spring MVC can be configured to only allow certain file types to be uploaded. This can be done using the 'spring.servlet.multipart.allowed-file-extensions' property in the application.properties file.

  3. Memory usage: When a file is uploaded, it is stored in memory by default. For large files, this can cause memory issues. To overcome this, Spring MVC provides options to store the uploaded file on disk or in a temporary location.

6. What is the difference between Spring MVC and Spring WebFlux?

They're two parallel web stacks with different concurrency models:

  • Spring MVCservlet-based, synchronous/blocking, thread-per-request. Mature, simple imperative code, the default for most apps. Runs on Tomcat/Jetty.
  • Spring WebFluxreactive, non-blocking, built on Project Reactor (Mono/Flux), event-loop based. Handles high concurrency with few threads; runs on Netty (or servlet 3.1+ async). Requires a fully reactive stack end-to-end (e.g. R2DBC, reactive clients) to pay off.
// MVC                              // WebFlux
@GetMapping("/u/{id}")             @GetMapping("/u/{id}")
User get(@PathVariable id){...}    Mono get(@PathVariable id){...}

When to choose which: MVC for typical CRUD/REST apps and teams that want straightforward imperative code; WebFlux for high-concurrency, streaming, or many slow upstream calls where blocking threads would be the bottleneck.

The crucial 2026 nuance: Java virtual threads (Boot 3.2+, spring.threads.virtual.enabled=true) let blocking MVC scale to huge concurrency cheaply — which removes the main reason many teams previously reached for WebFlux. So the modern answer is "MVC + virtual threads handles most high-concurrency needs; choose WebFlux when you genuinely need reactive/streaming semantics or backpressure."

↑ Back to top

Live mock interview

Mock interview: Spring Web MVC

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.