Prepare for Your Spring MVC Interview: Basic to Advanced Questions
Spring MVC is a powerful framework for building web applications in Java. This comprehensive guide covers 30 essential Spring MVC interview questions arranged by difficulty level – from basic concepts for freshers to advanced scenarios for experienced developers with 3-6 years of experience. Each question includes clear, practical answers with code examples where relevant.
Basic Spring MVC Questions (1-10)
1. What is Spring MVC?
Spring MVC is a Java framework that follows the Model-View-Controller (MVC) architectural pattern for building web applications. It separates application logic into three interconnected components: Model (data), View (presentation), and Controller (business logic).[1][2]
2. What are the key benefits of using Spring MVC?
Spring MVC provides clear separation of concerns, lightweight configuration, reusable business logic, customizable validation, and easy integration with other Spring modules. It simplifies development through annotation-based configuration and powerful request handling.[1][5]
3. What is DispatcherServlet in Spring MVC?
DispatcherServlet is the front controller in Spring MVC that receives all incoming HTTP requests and delegates them to appropriate controllers. It coordinates the entire request-response cycle.[2][3]
4. Explain the flow of a request in Spring MVC.
A client request reaches DispatcherServlet → HandlerMapping identifies the controller → Controller processes the request and returns ModelAndView → ViewResolver resolves the logical view name → View renders the response.[2][4]
5. What is the role of Controller in Spring MVC?
Controllers handle incoming web requests, process business logic, and return ModelAndView objects containing model data and view names. They are annotated with @Controller.[3][5]
6. What is @Controller annotation?
@Controller marks a class as a Spring MVC controller that handles HTTP requests. It tells Spring to scan this class for request mapping methods.[1][7]
7. What is a ViewResolver?
ViewResolver translates logical view names (returned by controllers) into actual view implementations like JSP files. InternalResourceViewResolver is commonly used for JSP views.[1][3]
8. What is Model in Spring MVC?
Model represents the data that the controller passes to the view for rendering. It acts as a container for view data and is accessible via Model, ModelMap, or ModelAndView.[1][3]
9. What is the difference between Model and ModelMap?
Model is an interface for adding attributes to the model. ModelMap extends LinkedHashMap and provides additional methods like get(), addAttribute(), and clear(). Both serve similar purposes.[1]
10. How do you configure DispatcherServlet in web.xml?
DispatcherServlet is configured as a servlet in web.xml that intercepts all requests. Here’s a basic configuration:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
[3][7]
Intermediate Spring MVC Questions (11-20)
11. What is @RequestMapping annotation?
@RequestMapping maps HTTP requests to handler methods in controllers. It supports URL paths, HTTP methods (GET, POST), headers, and parameters.[7]
12. Explain @PathVariable annotation with an example.
@PathVariable extracts values from URI template variables. Example:
@RequestMapping("/user/{id}")
public String getUser(@PathVariable("id") Long userId) {
// Process userId
return "user";
}
This maps /user/123 to userId=123.[1][7]
13. What is @RequestParam?
@RequestParam binds request parameters (query string or form data) to method parameters. Example: @RequestParam("name") String userName binds ?name=John to userName variable.[7]
14. What is a Form Backing Object?
A Form Backing Object (or Command Object) is a simple POJO that holds form data submitted by users. Spring automatically binds request parameters to object properties.[1][7]
15. How does data binding work in Spring MVC?
Spring automatically converts request parameters to Java object properties using PropertyEditor and ConversionService. Custom editors can be registered for complex types.[2]
16. What is BindingResult in Spring MVC?
BindingResult holds validation errors after data binding. It must immediately follow the target object parameter in controller methods.
public String processForm(@Valid User user, BindingResult result) {
if(result.hasErrors()) {
return "form";
}
return "success";
}
[1][7]
17. How do you perform form validation in Spring MVC?
Use @Valid with JSR-303 annotations (like @NotNull, @Size) on form backing objects, followed by BindingResult. Spring displays errors using form:errors tag.[1][2]
18. What is the difference between @Controller and @RestController?
@Controller is for traditional web applications returning views. @RestController combines @Controller and @ResponseBody, ideal for REST APIs returning JSON/XML data.[1]
19. What is @ResponseBody annotation?
@ResponseBody tells Spring to serialize the return object to HTTP response body (JSON/XML) instead of resolving it as a view name.[5]
20. Explain HandlerMapping in Spring MVC.
HandlerMapping maps incoming requests to appropriate controller methods based on URL patterns, HTTP methods, and other criteria. DefaultAnnotationHandlerMapping handles @RequestMapping.[2]
Advanced Spring MVC Questions (21-30)
21. What is the Front Controller pattern in Spring MVC?
DispatcherServlet implements the Front Controller pattern where a single servlet handles all requests, delegates to handlers, and centralizes request processing.[1][5]
22. How do you handle exceptions globally in Spring MVC?
Use @ControllerAdvice with @ExceptionHandler methods or implement HandlerExceptionResolver. Example:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public String handleUserNotFound() {
return "error/user-not-found";
}
}
[2]
23. Explain Spring MVC’s support for localization.
Spring MVC supports internationalization through ResourceBundleMessageSource, LocaleResolver (CookieLocaleResolver/SessionLocaleResolver), and locale-specific view resolution.[1]
24. What are Spring Form Tags and their advantages?
Spring provides form tags like <form:form>, <form:input>, <form:errors> that automatically bind to form backing objects, handle validation errors, and support CSRF protection.
25. How do you upload files in Spring MVC?
Use MultipartResolver (like CommonsMultipartResolver) and @RequestParam MultipartFile. Controller method:
@RequestMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
// Process file
return "success";
}
[2]
26. What is ModelAndView and when to use it?
ModelAndView holds both model data and view name. Use it when you need to set status codes, headers, or multiple model attributes explicitly.[5]
27. At Atlassian, how would you implement RESTful services using Spring MVC?
Use @RestController with @RequestMapping for HTTP methods (GET, POST, PUT, DELETE). Follow REST conventions with proper status codes and HATEOAS links where appropriate.[1]
28. Explain content negotiation in Spring MVC.
Spring MVC supports content negotiation through Accept header, URL extension (.json, .xml), or query parameter (?format=json). Configure ContentNegotiatingViewResolver.[2]
29. How do you achieve caching in Spring MVC controllers?
Use @Cacheable, @CacheEvict annotations on controller methods or enable caching with CacheManager. Works seamlessly with Spring’s caching abstraction.[2]
30. For a scenario at Zoho where high traffic hits your Spring MVC application, how would you optimize performance?
Implement caching with @Cacheable, use asynchronous processing with @Async, enable HTTP/2, optimize ViewResolver, use ContentCachingRequestWrapper for logging, and profile with Spring Boot Actuator.[2]
## Key Citations
[1] Indeed.com Spring MVC Interview Questions
[2] GeeksforGeeks Spring MVC Interview Questions
[3] YouTube Top 10 Spring MVC Questions
[4] Coursera Spring MVC Interview Guide
[5] Baeldung Spring MVC Questions
[6] InterviewBit Spring Questions
[7] in28minutes Spring Interview Guide