Spring MVC is a widely used Java framework for developing robust, scalable, and maintainable web applications. Based on the Model-View-Controller (MVC) design pattern, it simplifies request handling, business logic separation, and view rendering while integrating seamlessly with the Spring ecosystem.
- Provides flexible URL request mapping.
- Supports data binding and form validation.
- Integrates seamlessly with Spring Boot and Spring Security.
Spring MVC Interview Questions for Freshers
1. What is MVC?
MVC refers to Model, View, and Controller. It is an architectural design pattern, which governs the application's whole architecture. It is a kind of design pattern used for solving larger architectural problems.
MVC divides a software application into three parts that are:
- Model
- View
- Controller
2. What is Spring MVC?
Spring MVC is a sub-framework of Spring framework which is used to build dynamic web applications and to perform Rapid Application Development (RAD).
- It is built on the top of the Java Servlet API.
- It follows the Model-View-Controller Architectural design pattern.
- It implements all the basic features of the applicationscore Spring framework like IOC (Inversion of Control) and Dependency Injection (DI) etc.
3. Difference between Spring Boot and Spring MVC
The basic difference between Spring Boot and Spring MVC are given below:
Features | Spring Boot | Spring MVC |
|---|---|---|
| Build | It is a framework, that helps developers get started with Spring framework with minimal configuration. | It is a web framework built on the top of Java Servlet API. |
| Working | Using Spring Boot, it is easy to create stand-alone dynamic web applications and rapid application development. | It is a part of core Spring framework, which supports Spring's basic features and is used for building web applications using MVC architecture. |
| Productivity | Developers use Spring Boot to save time and increase productivity in developing stand-alone applications and Spring-based projects. | Developers use Spring MVC to create web applications running on a servlet container such as Tomcat. |
4. Explain Spring MVC Architecture.
Spring MVC Architectural Flow Diagram:
-660.png)
- The client sends an HTTP request to the DispatcherServlet (Front Controller).
- The DispatcherServlet uses Handler Mapping to locate the appropriate Controller.
- The Controller processes the request and returns a ModelAndView object.
- The DispatcherServlet sends the view name to the ViewResolver to resolve the actual view.
- The View renders the model data and returns the response to the client.
5. What are the Key Components of Spring MVC Architecture?
Spring MVC follows the Model-View-Controller (MVC) design pattern, where each component has a specific responsibility in processing a request and generating a response.
- DispatcherServlet: The front controller that receives all incoming HTTP requests and coordinates request processing.
- Controller: Handles client requests, processes business logic (directly or through services), and returns the appropriate view or response.
- Model: Holds the application data that is passed from the controller to the view.
- View: Displays the data to the user. It can be JSP, Thymeleaf, HTML, or a JSON response in REST applications.
- View Resolver: Maps the logical view name returned by the controller to the actual view file.
- Handler Mapping: Maps incoming requests to the appropriate controller method based on the request URL.
- Service Layer: Contains the business logic and acts as an intermediary between the controller and the repository.
- Repository (DAO): Interacts with the database to perform CRUD operations.
6. Explain the Model-View-Controller (MVC) Design Pattern.
MVC design pattern is a way to organize the code in our application. MVC refers to Model, View, and Controller.
- Model: Represents the application data and transfers it between the Controller and View.
- View: Displays the model data to the user.
- Controller: Handles incoming requests, processes business logic (through the service layer), and returns the appropriate view or response.
7. What is Dispatcher Servlet in Spring MVC?
DispatcherServlet is the Front Controller of the Spring MVC framework. It receives all incoming HTTP requests, routes them to the appropriate controller, and returns the appropriate response (view or data).
- Maps requests to the appropriate controller.
- Coordinates with Handler Mapping, View Resolver, and other MVC components.
- Returns the final view or response to the client.
8. Explain the five most used annotations in Spring MVC Project.
The most used five annotations in the Spring MVC project are:
@Controller: This annotation is used to create classes as controller classes and parallelly it handles the HTTP requests as well.
@Controller
public class GfgController {
// write code here }
@RequestMapping: To map the incoming HTTP requests with the handler methods inside the controller class, we use @RequestMapping annotation.
@RestController
public class GfgController {
@RequestMapping(value = "", method = RequestMapping.GET)
//write code here }
@RequestParam: To obtain a parameter from URI (Uniform Resource Identifier), we use @RequestParam annotation.
@GetMapping("/clients)
public String getClients(@RequestParam(name = "clientname") String name) {
//write code here }
@PathVariable: To extract the data from the URI path, we use @PathVariable annotation.
@GetMapping("/client/{clientName}")
public String getClientName(@PathVariable(name = "clientName") String name) {
//write code here }
@ModelAttribute: This annotation binds method parameter and refers to the model object.
@ModelAttribute("client")
public Client client() {
//write code here }
9. What is ViewResolver in Spring MVC?
In Spring MVC, ViewResolver is used to determine how a logical view name is received from a controller and maps that to an actual file. There are different types of ViewResolver classes. Some of them are defined below:
- InternalResourceViewResolver: It uses a prefix and suffix to convert a logical view name.
- ResourceBundleViewResolver: It uses view beans inside property files to resolve view names.
- XMLViewResolver: It also resolves view names in XML files to beans defined in the configuration file.
10. Difference between @Controller and @RestController
| Feature | @Controller | @RestController |
|---|---|---|
| Purpose | Used for Spring MVC web applications | Used for RESTful web services |
| Response | Returns a view (JSP, Thymeleaf, HTML) | Returns data (JSON, XML, etc.) |
| @ResponseBody | Must be added explicitly | Included automatically |
| View Resolver | Required | Not required |
| Primary Use | Web applications with UI | REST APIs and Microservices |
| Example | Login page, Dashboard | Employee API, Product API |
@RestController annotation encapsulates @Controller and @ResponseBody annotation.

11. What is WebApplicationContext in Spring MVC?
WebApplicationContext is a web-specific extension of the ApplicationContext that provides configuration and supports web-related features in Spring MVC. It is associated with the DispatcherServlet and manages web application beans.
- Contains the ServletContext information.
- Each DispatcherServlet has its own WebApplicationContext.
- Supports web-specific beans such as Controllers, ViewResolvers, and HandlerMappings.

12. What is DTO and Repository Interface in Spring MVC?
DTO: A DTO (Data Transfer Object) is a simple Java class used to transfer data between different application layers (such as Controller, Service, and Client). It contains only data fields along with getters and setters, without any business logic.
Note: DTO should not contain any additional logic, except the logic for encapsulation.
Repository Interface: A Repository Interface provides an abstraction for database operations. It interacts with the database and is typically created by extending interfaces like CrudRepository or JpaRepository.
Note: Repository implements any one of the pre-defined repositories like CRUD repository or JPA repository.
13. How to handle different types of incoming HTTP request methods in Spring MVC?
Spring MVC handles different HTTP request methods using @RequestMapping or specialized mapping annotations.
Supported HTTP Methods
- GET –> Retrieve data.
- POST –> Create new resources.
- PUT –> Update existing resources.
- DELETE –> Delete resources.
- PATCH –> Partially update resources.
For each request, run we can use separate annotations like @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping instead of passing the method inside the @RequestMapping annotation.
@GetMapping("/employees")
public List<Employee> getEmployees() {
return employeeService.getEmployees();
}
14. Difference between ApplicationContext and WebApplicationContext in Spring MVC
| Feature | ApplicationContext | WebApplicationContext |
|---|---|---|
| Purpose | Used for general Spring applications | Used specifically for Spring MVC web applications |
| Environment | Stand-alone applications | Web applications |
| ServletContext | Not available | Available |
| DispatcherServlet | Not associated | Associated with DispatcherServlet |
| Configuration | applicationContext.xml or Java Config | *-servlet.xml or Java Config |
| Example | Desktop/Console applications | Web applications, REST APIs |
Spring MVC Interview Questions for Intermediate
15. How to perform Validation in Spring MVC?
Validation ensures that user input is correct before processing it. Spring MVC provides multiple ways to perform validation.
Ways to Perform Validation
- Annotation-based Validation using @Valid, @NotNull, @NotBlank, @Email, etc.
- Custom Validation by implementing the Validator interface.
- Manual Validation using custom validation logic.
Advantages
- Prevents invalid data.
- Improves application security.
- Reduces runtime errors.
16. How to perform Exception Handling in Spring MVC?
Exception Handling is the process of handling runtime errors gracefully without crashing the application.
Ways to Handle Exceptions
@ExceptionHandler–> Handles exceptions within a controller.@ControllerAdvice–> Provides global exception handling across controllers.HandlerExceptionResolver–> Creates custom exception handling logic.- Logging Exceptions –> Helps in debugging and monitoring.
17. Difference between @RequestParam and @PathVariable annotations in Spring MVC
The difference table is given below:
| Feature | @RequestParam | @PathVariable |
|---|---|---|
| Source | Query parameters | URL path |
| URL Example | /users?id=101 | /users/101 |
| Required | Optional by default | Required by default |
| Used For | Optional request data | Resource identifiers |
| Example | @RequestParam("id") | @PathVariable("id") |
18. Explain Query String and Query Parameter in Spring MVC.
A Query String is the portion of a URL that appears after the ? symbol and contains one or more Query Parameters in the form of key-value pairs.
Query String: It contains key-value pairs that are separated by "&".
https://gfg.org/?path?key=value&key1=value1
Query Parameter: To access query parameters @RequestParam and @PathVariable annotations are used in a Spring MVC application. In a query string, the key-value pair is called the query parameter. Key: name of data and Value: actual data
19. Define the purpose of the @ModelAttribute annotation.
The @ModelAttribute annotation binds request data to a model object and makes it available to the view.
- Reduces manual data binding.
- Commonly used in Spring MVC form handling.
Example:
@ModelAttribute("employee")
public Employee getEmployee() {
return new Employee();
}
20. Difference between @RequestBody and @ResponseBody Annotation in Spring MVC
| Feature | @RequestBody | @ResponseBody |
|---|---|---|
| Purpose | Converts the HTTP request body into a Java object. | Converts a Java object into the HTTP response body. |
| Direction | Client → Server | Server → Client |
| Data Format | Reads JSON/XML from the request. | Returns JSON/XML in the response. |
| Used With | Method parameters | Method return type |
| Common Use | POST, PUT, PATCH requests | REST API responses |
Note: @RestController automatically applies @ResponseBody to all controller methods.
21. Explain the Multi Action Controller in Spring MVC.
Multi Action Controller in Spring MVC is a unique controller class (MultiActionController) that is used to handle multiple HTTP request types like GET, PUT, POST ETC. There are many advantages of Multi Action Controller.
- It reduces code duplication, simplifies maintenance, and increases flexibility.
- It manages and implements CRUD operations.
Note: Multi Action Controller is not a best option for complex logics.
Spring MVC Interview Questions For Experienced
22. Explain Spring MVC Interceptor.
A Spring MVC Interceptor intercepts HTTP requests before and after controller execution to perform common tasks such as logging, authentication, authorization, and request preprocessing.
- Used for logging and auditing.
- Can modify requests or responses.
- Implemented using the HandlerInterceptor interface.
Note: Common methods are preHandle(), postHandle(), and afterCompletion().
23. Explain the role/purpose of ContextLoaderListener in Spring MVC.
ContextLoaderListener initializes the root ApplicationContext when the web application starts and manages beans shared across the entire application.
- Loads application-wide beans.
- Initializes the application during startup.
- Shares beans across multiple DispatcherServlets.
24. How to enable CSRF protection in a Spring MVC Application?
CSRF (Cross-Site Request Forgery) protection prevents unauthorized requests from malicious websites. Spring Security enables CSRF protection by default.
Steps
- Step 1: Add the Spring Security dependency.
- Step 2: Enable CSRF in the security configuration (enabled by default).
- Step 3: Include the generated CSRF token in HTML forms.
- Step 4: Submit the token with every state-changing request (POST, PUT, DELETE).
Benefits
- Prevents forged requests.
- Protects user sessions.
- Improves application security.
Note: To disable CSRF for any specific URL, we can use @CSRFIgnore annotation.
25. How to use JSTL with Spring MVC?
JSTL stands for JavaServer Pages Standard Tag Library. It provides tags for working with web pages and its data. We can use JSTL with Spring MVC to simplify the development process.
Steps to Implementation:
- Step 1: JSTL Library dependencies need to be added.
- Step 2: Configure JSTL in Spring MVC by adding JstlViewResolver to the configuration file.
- Step 3: Use JSP (Java Server Pages) tags.
- Step 4: Spring MVC data access in JSTL.
JSTL tags can be combined with Spring Security tags to enhance the development process.
26. How to integrate the Database with the Spring MVC Project?
Database Integration is a very vital process in every project. To integrate a database with Spring MVC, follow the below steps:
- Step 1: Select the database and load driver.
- Step 2: Configure JDBC database connectivity/Configure Spring Data JPA
- Step 3: Create Beans (entity object)
- Step 4: DataSource Configuration
- Step 5: DAO Layer Implementation
- Step 6: Controller and Services of Spring MVC need to be used.
27. How to use SessionAttributes in Spring MVC?
SessionAttributes in Spring MVC is used to store model attributes in HTTP sessions and can retrieve them. For this, we use @SessionAttribute annotation. It avoids re-creating objects in every request. It can share data between multiple requests.
Steps to use SessionAttributes in Spring MVC:
- Step 1: Use @SessionAttribute to Controller class or method.
- Step 2: Add model attribute to session.
- Step 3: In other controller, access the session attributes.
28. What is Additional Configuration File in Spring MVC?
An Additional Configuration File in Spring MVC is used to store extra application or framework configurations separately from the main configuration.
- Helps organize application configuration.
- Can define beans, view resolvers, interceptors, etc.
- Improves maintainability and modularity.
29. Can we declare a class as a Controller? If yes, then explain how.
Yes . A class can be declared as a Controller by annotating it with @Controller.
- Handles incoming HTTP requests.
- Returns a view name or model data.
30. What is ModelInterface?
The Model interface is used to pass data from the Controller to the View.
- Transfers data to the view.
- Used to render dynamic content.
- Supports multiple attributes.
31. What is ModelMap?
ModelMap is an implementation of the Model interface that stores data as key-value pairs and passes it to the view.
- Extends LinkedHashMap.
- Used to transfer data to the view.
- Supports multiple model attributes.
32. Explain different ways to read data from the FORM in Spring MVC.
There are different ways to read data from the form in Spring MVC. Two of them are:
- @RequestParam: It binds individual form directly to method argument.
- @ModelAttribute: It binds the entire form to a POJO (Plain Old Java Object) class.
33. What is Form tag library in short?
The Spring Form Tag Library provides JSP tags to create forms and bind form data directly to Java objects.
- Supports automatic data binding.
- Integrates with Spring validation.
34. What do you mean by Bean Validation in Spring MVC?
Bean Validation is used to validate user input automatically using validation annotations before processing the request.
- Uses annotations like @NotNull, @Email, @Size, etc.
- Prevents invalid data.
- Improves data integrity
35. State the two annotations that are used to validate the user's input within a number range in MVC.
The two annotations that are used to validate the user's input within a number range in Spring MVC are:
- @Min: With this annotation the Integer value is required to pass, and it specifies the minimum value allowed.
- @Max: With this annotation the Integer value is required to pass, and it specifies the maximum value allowed.