Spring MVC is the foundational web layer of the Spring Framework, and it remains a favourite topic in Java developer interviews at every level. Even in a world dominated by Spring Boot auto-configuration, interviewers probe Spring MVC knowledge to gauge whether a candidate truly understands what happens under the hood. This guide covers the 40 most-asked Spring MVC interview questions, organised from core concepts through advanced topics, each with a concise, interview-ready answer.
Core Concepts
1. What is Spring MVC?
Spring MVC is a request-driven web framework built on the Model-View-Controller pattern. It uses a central DispatcherServlet to route HTTP requests to handler methods, resolve views, and write responses. It is part of the spring-webmvc module and works on top of the Servlet API.
2. What is DispatcherServlet?
DispatcherServlet is the front controller. Every request enters through it, which then delegates to HandlerMapping (to find the right controller method), HandlerAdapter (to invoke it), and ViewResolver (to render the response). In Spring Boot it is registered automatically.
3. Describe the Spring MVC request lifecycle.
- Browser sends HTTP request to
DispatcherServlet. HandlerMappingmaps the URL to a controller method.HandlerAdapterinvokes the method, resolving arguments (path variables, request bodies, etc.).- Controller executes business logic and returns a
ModelAndViewor writes directly to the response body. ViewResolverresolves the view name to a template (Thymeleaf, JSP, etc.) if applicable.- View renders the response and sends it back to the client.
4. What is the difference between @Controller and @RestController?
@Controller marks a class as a Spring MVC controller; return values are typically view names resolved by a ViewResolver. @RestController is a shortcut for @Controller + @ResponseBody; every method writes its return value directly to the HTTP response body (usually JSON), bypassing view resolution.
5. What does @RequestMapping do?
It maps HTTP requests to handler methods or classes. Attributes include value (URL pattern), method (HTTP verb), consumes, produces, params, and headers. Shorthand annotations include @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, and @PatchMapping.
6. What is the difference between @RequestParam and @PathVariable?
@PathVariable binds a URI template variable (e.g. /users/{id}). @RequestParam binds a query parameter or form field (e.g. /users?page=2). Both support required and defaultValue attributes.
7. How does @RequestBody work?
It instructs Spring to deserialise the HTTP request body into a Java object using a registered HttpMessageConverter. For JSON payloads, Jackson’s MappingJackson2HttpMessageConverter is used by default.
8. What is @ResponseBody?
It tells Spring to serialise the method return value directly into the HTTP response body instead of resolving it as a view name. The correct HttpMessageConverter is chosen based on the Accept header.
9. What is ModelAndView?
A holder object that carries both the model (a Map of attributes passed to the view) and the view name or view instance. Used primarily with server-side template rendering (Thymeleaf, JSP). For REST APIs, returning a plain object with @ResponseBody is preferred.
10. What is ViewResolver?
A strategy interface that translates a logical view name (returned from a controller) to an actual View implementation. InternalResourceViewResolver maps names to JSP paths; ThymeleafViewResolver maps them to Thymeleaf templates.
Data Binding & Validation
11. How do you validate request data in Spring MVC?
Annotate the model class with Bean Validation (Jakarta) constraints (@NotNull, @Size, @Email, etc.) and add @Valid or @Validated to the controller parameter. Bind errors are captured in a BindingResult parameter immediately following the model.
12. What is @ModelAttribute?
On a method parameter, it binds form fields or query parameters to a model object. On a method itself, it populates a model attribute that is available to all handler methods in the controller (e.g. to pre-populate a dropdown list).
13. What is @InitBinder?
It annotates a method that customises data binding for a specific controller. Common uses include registering custom property editors (e.g. date format parsers) or restricting which fields can be bound to prevent mass-assignment attacks.
14. How does Spring MVC handle type conversion?
Spring uses a ConversionService backed by built-in and custom Converter / Formatter implementations. For example, a String path variable is automatically converted to a Long if the method parameter type is Long.
Exception Handling
15. How do you handle exceptions globally in Spring MVC?
Annotate a class with @RestControllerAdvice (or @ControllerAdvice) and add @ExceptionHandler methods for each exception type. The handler returns an appropriate HTTP status and error body.
16. What is @ExceptionHandler?
It designates a method as an exception handler. When the specified exception type is thrown from any request in scope (controller or global advice), Spring invokes this method to produce the error response.
17. What is ResponseEntityExceptionHandler?
A convenient base class in Spring MVC that already handles many standard Spring exceptions (e.g. MethodArgumentNotValidException, HttpMediaTypeNotSupportedException). Extend it and override handleExceptionInternal() or specific handler methods to customise the error response format.
REST and HTTP
18. What is ResponseEntity?
A generic wrapper that gives full control over the HTTP response: status code, headers, and body. Use it when you need to return a 201 Created with a Location header, or a 204 No Content with no body.
19. How do you return a 404 from a controller?
Either return ResponseEntity.notFound().build(), or throw an exception annotated with @ResponseStatus(HttpStatus.NOT_FOUND), or handle the exception in a @ExceptionHandler that returns ResponseEntity.status(404).build().
20. What is content negotiation in Spring MVC?
The process of selecting the response format (JSON, XML, CSV) based on the client’s Accept header or URL suffix. Spring’s ContentNegotiatingViewResolver and the produces attribute of @RequestMapping drive this mechanism.
21. How do you enable CORS in Spring MVC?
Add @CrossOrigin to a controller or method for per-endpoint control, or configure a global policy via WebMvcConfigurer.addCorsMappings() to apply uniformly across all endpoints.
22. What is HttpMessageConverter?
A strategy interface that converts HTTP request bodies to Java objects (reading) and Java objects to HTTP response bodies (writing). The framework picks the converter based on the Content-Type / Accept headers and the parameter type.
Interceptors & Filters
23. What is a HandlerInterceptor?
A Spring MVC concept that hooks into the request processing pipeline with three callbacks: preHandle() (before the controller), postHandle() (after the controller but before view rendering), and afterCompletion() (after everything, including errors). Used for logging, auth checks, and metrics.
24. What is the difference between a Filter and a HandlerInterceptor?
A Servlet Filter operates at the Servlet container level and can intercept any request including static resources; it has no knowledge of Spring beans. A HandlerInterceptor operates inside the Spring MVC context, has access to Spring beans via injection, and can access the matched handler object.
Advanced Topics
25. What is @SessionAttributes?
A class-level annotation that stores specific model attributes in the HTTP session between requests. Useful for wizard-style multi-step forms. Cleared by calling SessionStatus.setComplete().
26. What is @CookieValue?
Binds a specific HTTP cookie value to a method parameter. Supports required and defaultValue like other binding annotations.
27. What is @RequestHeader?
Binds an HTTP request header value to a method parameter. For example, @RequestHeader("X-API-Key") String apiKey reads the custom header from every incoming request.
28. What is Multipart file upload in Spring MVC?
Files uploaded via multipart/form-data are bound to MultipartFile parameters annotated with @RequestParam. Configure spring.servlet.multipart.max-file-size in application.properties to control upload limits.
29. What is @Async in a Spring MVC controller?
Return a Callable<T> or CompletableFuture<T> from a controller method to process the request asynchronously on a different thread, freeing the Servlet container thread immediately. Spring MVC’s async support must be enabled on the DispatcherServlet.
30. What is Server-Sent Events (SSE) in Spring MVC?
Return a SseEmitter from a controller method to push a continuous stream of events to a browser client over a single long-lived HTTP connection. Used for real-time dashboards, notifications, and progress indicators.
31. How do you configure Spring MVC without XML?
Implement WebMvcConfigurer in a @Configuration class and override the methods you need (e.g. addViewResolvers(), addInterceptors(), addCorsMappings(), configureMessageConverters()). Annotate with @EnableWebMvc to take full control (note: this disables Spring Boot’s auto-configuration).
32. What does @EnableWebMvc do?
It imports DelegatingWebMvcConfiguration, which registers the full set of Spring MVC infrastructure beans. In a Spring Boot project, adding @EnableWebMvc switches off Boot’s auto-configuration, so use it only when you need complete manual control.
33. What is the difference between @Component, @Service, and @Repository in the context of Spring MVC?
All three are stereotypes that trigger component scanning. @Service conventionally marks the business-logic layer; @Repository marks the data-access layer (and enables persistence exception translation); @Component is the generic fallback. They are functionally equivalent for DI purposes.
34. What is Flash Attributes in Spring MVC?
Attributes stored in the session only for the next request, then automatically removed. They are used in the Post-Redirect-Get pattern to pass success/error messages across a redirect without polluting the URL.
35. How do you unit-test a Spring MVC controller?
Use MockMvc. With @WebMvcTest, Spring loads only the web layer; with MockMvcBuilders.standaloneSetup(controller), no Spring context is needed at all. Assertions use .andExpect() to verify status codes, JSON paths, and headers.
36. What is the role of HandlerMapping?
It maps incoming requests to handler objects (controller methods). Spring provides RequestMappingHandlerMapping (annotation-driven), BeanNameUrlHandlerMapping, and RouterFunctionMapping (functional style). Multiple mappings coexist and are tried in order.
37. What is the difference between redirect: and forward: in view names?
Prefixing a view name with redirect: sends a 302 redirect to the client; the browser makes a new GET request to the specified URL. Prefixing with forward: performs a server-side forward; the same request is dispatched to another URL internally without the client knowing.
38. What is @MatrixVariable?
Binds semi-colon delimited key-value pairs embedded in URL path segments, e.g. /cars/42;color=red;seats=5. Requires removeSemicolonContent=false in the MVC configuration to enable.
39. How does Spring MVC support i18n (internationalisation)?
Register a LocaleResolver bean (AcceptHeaderLocaleResolver, CookieLocaleResolver, or SessionLocaleResolver) and a MessageSource backed by .properties files per locale. Use LocaleChangeInterceptor to allow users to switch locale via a request parameter.
40. What is the difference between Spring MVC and Spring WebFlux?
Spring MVC is synchronous and imperative, built on the Servlet API. Spring WebFlux is reactive and non-blocking, built on Project Reactor and Netty. WebFlux uses Mono and Flux return types and suits high-concurrency I/O-bound workloads. Spring MVC is the right choice for most traditional web applications.
See Also
- Building a REST API with Spring Boot
- Mastering ETag Cache Control in Spring Boot REST APIs
- Resilience4j Circuit Breaker in Spring Boot
Conclusion
Mastering these 40 Spring MVC interview questions will prepare you for conversations at any level, from junior roles that test annotations and the request lifecycle through senior positions that explore async handling, interceptors, and architectural trade-offs. The key insight interviewers look for is understanding not just what an annotation does, but why the framework was designed that way and what happens under the hood when a request arrives at DispatcherServlet.