Spring MVC Interview Questions

spring MVC interview questions

About Spring MVC

The model-view-controller (MVC) architecture for Spring Web is built on a DispatcherServlet that distributes requests to handlers and supports file uploading, configurable handler mappings, display resolution, locale resolution, and theme resolution. The default handler, which provides a variety of customizable handling techniques, is based on the @Controller and @RequestMapping annotations. Thanks to the @PathVariable annotation and other innovations in Spring 3.0, you can now develop RESTful Web sites and applications using the @Controller method.

Get Explore Now

Enhance your Knowledge and skills with our Training programs and make productive learning.

Spring MVC Interview Questions and Answers

1.What is Spring MVC?

Web applications are created using a Java framework called Spring MVC. This design pattern is known as Model-View-Controller. Therefore, Spring MVC is a combined Model View Controller and Spring framework. It implements all of the fundamental elements of the core spring framework, including Dependency Injection and Inversion of Control.
Spring MVC makes it simple to create apps. The input logic, business logic, and UI logic of the program are separated by the MVC pattern, which also offers loose connectivity between these elements.

2.What exactly is MVC?
  • The MVC architectural design pattern (Model-View-Controller) is a software design pattern. It splits the processes of a program into three interconnected parts: Model, View, and Controller.
  • The Model represents the application’s essential data. They typically consist of POJO (Plain Old Java Object).
  • The View is in charge of displaying the model’s data and producing HTML output that the client’s browser can understand.
  • The application’s business logic is stored in the Controller.
  • This method enables parallel development and reusability. MVC is popular because it splits the application logic and user interface layers, allowing for the division of responsibilities.
3.How does spring MVC work?

The steps below will help you understand the Spring MVC workflow.

  • The Dispatcher Servlet, which serves as the front controller, intercepts all incoming requests.
  • The Dispatcher Servlet then sends the request to the controller after retrieving an entry of handler mapping from the XML file.
  • The controller returns the Model and View objects.
  • The Dispatcher Servlet verifies the view resolver’s entry in the XML file and then calls the relevant view component.
4.Advantages of the Spring MVC
  • The container is used for application development and deployment, and it contains a lightweight servlet.
  • It enables faster and more parallel development.
  • The application’s development grows more rapidly.
  • It is simple for several developers to work on.
  • It is easier to update the application.
  • It is easier to debug because the application has various levels.
5.Disadvantages of the Spring MVC

The process of creating apps using this pattern is quite difficult.
It is not suitable for tiny applications as it has an impact on the application’s performance and design.

6.What is Spring Boot?

spring boot
Spring Boot is another well-known Java framework used to build apps. It primarily focuses on the development of microservices. The microservice architecture enables independent application development and deployment. It is an improved version of the Spring framework that assists in the reduction of development time. Spring boot-based apps are enterprise-ready.
Spring boot has four layers, which are listed below:
Presentation layer:The front-end portion of the presentation layer handles HTTP requests. This request is then verified and forwarded to the business layer.
Business layer: This layer provides business logic; it includes service classes and handles authentication and validation.
Persistence layer: The persistence layer consists of the storage logic that converts business objects into database rows.
Database layer: This layer handles the CRUD (Create, Retrieve, Update, and Delete) tasks.

7.Spring Boot vs. Spring MVC
Spring MVC Spring Boot
A Model, View, and Controller-based framework called Spring MVC is used to create web applications. One of the most popular frameworks for developing REST APIs is Spring Boot.It is constructed over the typical spring structure. It is used to create independent web spring apps.
Many configurations are needed for this framework, including configurations for the View Resolver and the Dispatcher Servlet. With the help of its Auto-configuration function, Spring Boot manages setups automatically.
For the features to function, each dependency has to be specified separately. Spring Booth contains the concept of starters; once it is added to the classpath, it will provide all the dependencies required for creating a web application.
Spring MVC makes it simple to create apps. With capabilities like auto-configuration and starters, Spring Boot enables the rapid and simple development of apps.
Productivity decreases Since it takes time to properly understand the dependency add-ons. Productivity rises when development time is less.
For JAR packaging, Spring MVC requires a large amount of manual configuration. Spring Boot allows the embedded server to execute the feature independently.
The Spring MVC framework needs a deployment description to function. The Spring Boot framework does not require a deployment descriptor.
Model, View, Controller, and Front Controller are the four elements of the Spring MVC framework (Dispatcher Servlet class). Spring Boot has four layers: the Presentation layer, the Business layer, the Persistence layer, and the Database layer.
Spring MVC lacks a powerful batch-processing feature. The Spring Boot framework has strong batch processing capability.
A deployment description is required for Spring MVC. Spring Boot does not require the use of deployment descriptors.
8.What is Spring MVC annotations?

Spring Annotations are a type of metadata that contains information about an application. Annotations are used to add extra information to a program. It has no direct effect on the performance of the code they annotate. It does affect the performance of the compiled application. In general, the spring framework supports six different sorts of annotations.

The following are some of the most popular Spring MVC annotations.
@Controller Annotation
This annotation acts as a specialization of @Component and allows implementation classes to be automatically discovered via classpath scanning. We can easily identify any of our Spring MVC controller classes with this annotation.
@RestController Annotation
This annotation is helpful for annotatingluence our RESTful controllers.

public class MyRestController {
The @RequestParam annotation makes it simple to map these parameters at the controller level, allowing us to link an HTTP request parameter to the method parameter.
This annotation is used in the Spring MVC Controller to map the web request methods. By utilizing its given attributes, we may additionally modify it:
  • Method: PUT, GET, POST, DELETE, or PATCH are examples of HTTP request methods.
  • Params: filtering the request using the HTTP parameters.
  • Headers: filter the request depending on the HTTP headers.
  • Produces: specifies the HTTP response’s media type
  • Consumes: identifies the HTTP request’s media type
9.What is the Spring MVC life cycle?

spring boot MVC lifecycle

  • There is a Front Controller pattern, and the Spring MVC Front Controller is Dispatcher Servlet. Spring controls the whole life cycle for each incoming user request, as detailed below.
  • In the first stage, Dispatcher Servlet will receive the request.
  • Dispatcher Servlet uses Handler Mapping to dispatch the request by mapping the @Controller class associated with the provided request.
  • The request is passed to the @Controller, who processes it by running necessary methods and returning a Mode and View object (which contains both Model data and View name) to the Dispatcher Servlet.
  • The model object is now sent to the View Resolver, which resolves and retrieves the actual view page.
  • The Model object will be sent to the View page by Dispatch for the result to be shown and the Response to be created.
  • Dispatcher Servlet then sends the response to the browser.
10.Brief Introduction to Dependency Injection.

Dependency injection is a crucial part of Spring frameworks that supposedly injects objects with dependencies that assist in the responsible management of the components which already exist in the container.
Spring Dependency Injection is classified into two categories.
They are as follows:
Injection of Setter Dependency (SDI): This is the less complicated of the two DI methods. The DI will be injected using setter and/or getter methods in this case. To configure the DI as SDI in the bean, use the bean-configuration file. The property to be set with the SDI is declared in the bean-config file under the property> tag.
Injection of Constructor Dependency (CDI): The DI will be inserted with the help of constructors in this case. To set the DI as CDI in the bean, use the bean-configuration file. The property to be set with the CDI is specified in the bean-config file inside the constructor-arg> tag.

11.Controller’s role in Spring MVC

Controller methods are the final endpoint for a web request in Spring MVC. After being called, the controller method begins processing the web request by connecting with the service layer to finish the necessary tasks. The types of controllers in spring MVC are as follows.

  • The basic controller.
  • Simple Form Controller.
  • Multi-Action Controller
  • Wizard Form Controller
  • Abstract Command Controller

Spring MVC Interview Questions for fresher

1.What exactly is a DispatcherServlet?

The DispatcherServlet is a Front Controller and a key component of the Spring MVC web framework. A Front Controller is a common structure in web applications that gets requests and sends them to other components of the program for processing. The DispatcherServlet serves as a single point of entry for client demands to the Spring MVC web application, passing them on to the relevant Spring MVC controllers for processing. DispatcherServlet is a front-end controller that assists with view resolution, error handling, locale resolution, theme resolution, and other tasks. The Dispatcher Servlet, like any other Servlet class, must be defined in the deployment descriptor or web.xml file.

2.What are the benefits of using Spring MVC?

Spring MVC allows us to design and thoroughly analyze our applications quickly because of the clear separation of responsibilities. View Resolvers, Controllers, Model and View, Views, Models, and Session Attributes are all completely separate entities that are only responsible for one aspect. As a result, MVC gives us a lot of flexibility. It’s built on interfaces with supplied implementation classes, and we can use custom interfaces to customize every part of the framework. Another important point is that we are not limited to single-view technology, but rather have the option of choosing which ones we want.

3.Is a spring boot required before spring MVC?

It is not necessary to study Spring MVC before beginning with Spring Boot, but it is beneficial to be knowledgeable about it. If you are familiar with Java, Maven, and Gradle, you are qualified to learn spring boot. Spring boot is easy to learn.

4.Which is better in comparison, Spring Boot or Spring MVC?

Although working with Spring Boot is much more comfortable than spring MVC, your decision may also be influenced by the kind of application you are developing. Both of these frameworks offer advantages over the other. For instance, Spring MVC is a fantastic option for creating modular web applications since it skips the overlapping process of managing HTTP requests. On the other hand, by minimizing the number of configurations, Spring Boot assists in time and effort savings. The use of annotation to develop an application in both types of technology is one common practice that might create confusion.

5.Is it possible to use spring MVC with spring boots?

Yes, Spring MVC and Spring Boot can be used together. You must include the spring-boot-starter dependency in your pom.xml file to create and run a Spring MVC web application in spring boot.

6.How to start utilizing spring?

To start using Spring, the following steps should be taken:

  • Download Spring and any dependencies from the Spring website.
  • Create an application context XML file to define the beans and their dependencies.
  • Combine application context XML with web.xml.
  • After the application has been deployed, run it.
7.What are the different modules used in the spring framework?

AOP (Aspect Oriented Programming), DAO and JDBC abstraction, The container Core, MVC framework, application context, Object/Relational mapping integration, and Web module.

8.What is the AOP module?

AOP is used to create aspects for Spring applications. It also supports metadata programming in Spring.

9.Which annotations are used to handle various sorts of incoming HTTP request methods?

The annotations listed below are used to handle various sorts of incoming HTTP request methods:

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @PatchMapping
  • @DeleteMapping
10.What information does an additional configuration file in a Spring MVC application contain?

The properties information is contained in an additional configuration file in the Spring MVC application. This file may be produced as an XML file or as a properties file. We specify the base package and view resolver in this file, where DispatcherServlet looks for the controller classes and views the component’s path. It can, however, contain a variety of additional configuration attributes.

11.What is the Model interface’s role in Spring MVC?

The Model interface acts as a container for the application’s data. Data in this application can take any form, including objects, texts, database information, and so on.

Spring MVC interview questions for experienced

1.In Spring MVC, how do you declare a class as a controller class?

To define a class as a controller class, use the @Controller annotation. This annotation must be specified on the class name. As an example:

class Demo  
2.What is the @PathVariable annotation in Spring MVC for?

The @PathVariable annotation can be used to extract the URI template value. It is passed as a parameter to the handler method.

public String handler(@PathVariable("id") String s, Model map)  
3.What does the @ResponseBody annotation do in Spring MVC?

The @ResponseBody annotation is used to automatically serialize the returned object in JSON and attach it to the HTTP response body. It is not necessary to call the model in this case.

public ResponseHandler display(  
@RequestBody ShowForm form) {  
return new ResponseHandler("display form");  
4.In Spring MVC, what do you mean by ModelAndView?

The ModelAndView class contains both a Model and a View, where the Model represents the data and the View represents how that data is shown. This class returns both the model and the view as a single value.

5.What exactly is ModelMap in Spring MVC?

ModelMap is a class that offers Map implementation. It is an extension of the LinkedHashMap class. It allows you to send a set of values as if they were on a Map.

6.What exactly is the Spring MVC form tag library?

The form tags used in Spring MVC can be considered as data binding-aware tags that can automatically bind data to Java objects or beans and retrieve it from them. A web page’s adjustable and reusable building elements are these tags. It offers view technologies, which make it simple to create, read, and update the data.

7.What exactly do Spring MVC validations mean?

One of the most significant elements of Spring MVC is validation, which is used to limit the user’s input. To validate the user’s input, Spring 4 or above and the Bean Validation API must be used. Spring validations may be used to validate both server-side and client-side applications.

8.What is the @Valid annotation in Spring MVC used for?

The @Valid annotation is used to add validation criteria to the object that is given.

9.In Spring MVC, how can I validate a user’s input inside a numeric range?

We may validate the user’s input inside a number range in Spring MVC Validation by using the following annotations: –
@Min annotation – The @Min annotation requires an integer value to be given. This value must be equal to or larger than the user input.
@Max annotation – The @Max annotation requires an integer value to be given. This value must be equal to or less than the user input.

10.What do Spring MVC validations use BindingResult for?

The information about validations is contained in the interface called BindingResult.
For example:

 public String submitForm( @Valid @ModelAttribute("emp") Employee e, BindingResult br)  
            return "viewpage";  
        return "final";  
11.What methods does Spring MVC have for reading data from forms

The data can be read from the form in the following methods:

  • HttpServletRequest interface – The javax.servlet.HTTP package has an interface called HttpServletRequest. Similar to Servlets, Spring’s HttpServletRequest may be used to read user-provided HTML form data.
  • @RequestParam annotation – The @RequestParam annotation automatically links the form data to the parameter existing in the method that is supplied after reading the data from the form.
  • @ModelAttribute annotation – The @ModelAttribute annotation links a specified model attribute to a method parameter or its return value.
12.What exactly is the Bean Validation API?

Bean validation API

  • The Bean Validation API is a Java language for applying constraints to object models using annotations. We can check a length, number, regular expression, and so on here. In addition, we can provide custom validations.
  • Because the Bean Validation API is only a specification, it necessitates implementation. As a result, Hibernate Validator is used. The Hibernate Validator is a full compliance JSR-303/309 solution that allows application restrictions to be expressed and validated.
13.In the Spring MVC framework, what does a Controller do?

A Controller class is in charge of handling various types of client requests depending on request mappings. Using the @Controller annotation, we can construct a controller class. It is often used in combination with the @RequestMapping annotation to specify handler methods for specific URI mapping.

14.What is the Spring MVC controller’s default scope?
  • By default, Spring MVC controllers are singletons, which means that any controller object variable or field is shared across all requests and sessions.
  • If the object variable should not be shared between requests, add the @Scope(“request”) annotation above your controller class declaration to build an instance for each request.

This article is covered by Top 35+ Spring MVC interview questions and answers for freshers and experienced candidates who can succeed in their Java Spring MVC careers. We hope to clear up your doubts and guide you in the right direction. Good Luck with your Spring MVC interview.