Spring MVC Interview Questions and Answers List in 2020

Today, in this article, we will go through our list of most frequently asked Spring MVC interview questions and answers.

Current article is part of our series on Spring Interview Questions.

Spring MVC is one of the favorite topic in a Java interview. So, let’s dive in straight away.

spring mvc interview questions and answers

Spring MVC Interview Questions and Answers

1. What is Spring MVC?

Spring MVC is the part of Spring Framework project.

Spring MVC facilitates us with MVC design pattern. On top of that, it provides additional ready-to-use capabilities.

2. What is MVC design pattern?

MVC stands for Model-View-Controller.

In this pattern, Controller sits between view and model to communicate between them.

Given this, view or front-end does not need to know anything about the back-end service or business logic and vice-versa.

3. What are the advantages of MVC design pattern?

  1. Loose Coupling: An application’s front-end and back-end becomes loosely coupled. Change one and it should not impact other, given the communication contract is same.
  2. Faster Development: With MVC, we get the separation of concerns between front-end and back-end. Once we define the contract between them, multiple developers can start working on them in parallel.

4. What are the advantages of using “Spring MVC”?

  1. Spring MVC is the most popular and comprehensive implementation of MVC pattern in java world.
  2. It has very big and matured community. This helps is figuring out issue we might face in development phase.
  3. We can use other Spring modules like dependency injection and AOP without thinking about the compatibility issues.
  4. Spring MVC provides a lot of components which helps in achieving separation of concerns. You can choose which components to use and which to not. In this way it provides flexibility in our application development approach.
  5. We can use Spring IoC in conjunction with Spring MVC and other Spring technologies, which makes it achieve loose coupling at another level.
  6. With the above, it becomes very easy and efficient to create web applications.
  7. Separation of concerns combined with loose coupling and good cohesiveness, it becomes very easy to unit test the different components.

5. Could you name the list of different Spring MVC components?

Spring MVC provides us many concepts and components. According to our goal, we can choose different components out of it in.

Spring MVC architecture Components

Some of the popular components are given below:

  1. Dispatcher Servlet
  2. Controllers
  3. HandlerMapping
  4. Interceptors
  5. ViewResolver
  6. LocaleResolver
  7. ThemeResolver
  8. MultipartResolver
  9. Views
  10. Models
  11. ModelAndView

6. What is DispatcherServlet?

DispatcherServlet is the Front Controller of Spring MVC framework. It’s responsibilities lies in line with a typical front controller, which is:

Handling all incoming and outgoing requests of an application and delegating the requests to proper components.

7. What is the Front Controller Pattern?

Note: Nail this question and you will build up your reputation in the interview.

Front controller pattern is one of the architectural design patterns which MVC frameworks use to implement the separation of concerns in an efficient manner.

In Front Controller Pattern, front controller is the central servlet which handles “all the requests coming in and response going out of the application”.

front controller with Spring MVC in Servlet engine

After receiving the request, front controller then delegates the request to appropriate handler or interceptor.

After everything is done on the request part, front controller then sends the response back to the UI.

As front controller acts as the ‘single‘ point of entry and exit to an application, all the configurations and customization can be done via. this central point. As a result of this, it gets very easy for both framework creators and framework users (the developers) to implement and use it.

8. What are the advantages of front-controller pattern?

  1. Central point of configuration: All the application wide settings or configuration like session, caching, localization etc. can be handled from single place.
  2. No boilerplate code: As we do not need to do common things again and again, we do not need to have boilerplate code at so many places.
  3. Better Cohesiveness: It helps achieve better cohesiveness to the internal components as they will just focus on their task.

9. What is Spring MVC WebApplicationContext?

WebApplicationContext is an IoC ApplicationContext in the web development environment.

WebApplicationContext inherits from ApplicationContext.

Hence, in addition to the functionalities provided by ApplicationContext, it can also handle thing like:

  1. Communication between ServletContext and IoC container.
  2. Handling of all the servlets associated with the context.
Spring Web MVC Context Hierarchy

10. What is Controller in Spring MVC Framework?

Controller denotes the ‘C’ in MVC.

Controllers are components in Spring Framework which handles the user requests coming from the View.

As we have Front Controller which handles all the incoming and outgoing requests of an application, we also have request specific Controller which handles requests delegated by Front-Controller.

Under-the-hood, a Controller is a Servlet.

11. What is @Controller annotation?

@Controller is a class level annotation. By marking a class with @Controller annotation, we are telling the IoC container to treat this class like a Controller.

12. What is the difference between @Controller and @RestController annotation in Spring MVC?

While working with @Controller marked class, if we want to write the response type in HTTP response body, we mark the method, which is sending the response, with @ResponseBody annotation.

With @RestController, we do not need to write the @ResponseBody for each such method. It is already included in the @RestController annotation.

Note: This is among the most frequently asked Spring MVC interview questions.

13. What is @RequestMapping annotation in Spring MVC?

@RequestMapping is a class level as well as a method level annotation. It is used to map a HTTP request to the method.

It takes HTTP request URL as input. For example:

@Controller
class ArticleController {

  @RequestMapping("/article/header")
  public String handleHeaderRequest() {
    //method logic
  }

  @RequestMapping("/article/footer")
  public String handleFooterRequest() {
    //method logic
  }
}

If all the methods in a controller handles URL with some common Prefixes like in our case “/article”, we can make it common by using @RequestMapping annotation at class level like below:

@Controller
@RequestMapping("/article")
class ArticleController {

  @RequestMapping("/header")
  public String handleHeaderRequest() {
    //method logic
  }

  @RequestMapping("/footer")
  public String handleFooterRequest() {
    //method logic
  }
}

14. What is @RequestParam annotation in Spring MVC?

@RequestParam annotation is used to map the query data in the HTTP URL to the method parameter of the @RequestMapping annotated method.

For example:

If we have a URL like http://something.com/article?id=3 to handle, where the number is a variable, we can do something like this:

@Controller
class ArticleController {

  @RequestMapping("/article")
  public String handleHeaderRequest(@RequestParam Integer id) {
    //method logic
  }

}

15. How does @PathVariable annotation work in Spring MVC?

@PathVariable annotation is used to map the variable data in HTTP URL itself to the method parameter of the @RequestMapping annotated method.

For example:

If we have a URL like http://something.com/article/3 to handle, where number is a variable, we can do something like this:

@Controller
class ArticleController {

  @RequestMapping("/article/{id}")
  public String handleHeaderRequest(@PathVariable Integer id) {
    //method logic
  }

}

16. What is @RequestBody annotation in Spring MVC?

@RequestBody annotation is used to map HTTP POST request body to a java object which is typically called Model in this context.

Serialization and de-serialization of the data happens automatically.

It is used inline with method parameters.

17. What is @ResponseBody annotation in Spring MVC?

@ResponseBody annotation is a method level annotation.

By marking a method in a @Controller with @ResponseBody makes Spring do the following:

  • It serializes the Java object returned from the method to JSON object.
  • It then passes this JSON object object in HTTPResponse to sent back to the client.

Note: Spring MVC Interview Questions on @RequestBody, @ReponseBody, @RequestParam, @PathVariable are all related to the communication between UI and @Controller.

18. What is @EnableWebMVC annotation?

@EnableWebMVC annotation is used if we are using Java Based Configuration to get the support for MVC.

In short, it is an alternate to <mvc: annotation-driven> used in XML based configuration.

@EnableWebMVC is used in conjunction with @Configuration annotation.

19. How to Get ServletContext and ServletConfig Objects in a Spring Bean?

Note: This question is simple but again one of the frequent Spring MVC Interview questions in the interview.

It can be done in two ways:

  1. By using the Spring *Aware interfaces.
  2. By using the @Autowired annotation.

Using ServletContextAware and ServletConfigAware:

@Controller
public class AController implements ServletContextAware, ServletConfigAware {
 
    private ServletContext context;
    private ServletConfig config;
 
    @Override
    public void setServletConfig(final ServletConfig servletConfig) {
        this.config = servletConfig;
 
    }
 
    @Override
    public void setServletContext(final ServletContext servletContext) {
        this.context = servletContext;
    }
}

Using @Autowired annotation:

@Controller
public class AController {
 
    @Autowired
    private ServletContext context;
    @Autowired
    private ServletConfig config;
 
}

Use of Spring Aware interfaces is discouraged, as it makes our application dependent on the Spring API.

20. What’s the difference between @Component, @Controller, @Repository & @Service annotations in Spring MVC?

@Component is a generic annotation while..

@Controller, @Service and @Repository are specific variants (Alias) of @Component.

All three are meta-annotations of @Component annotation as can be seen in example:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
	@AliasFor(annotation = Component.class)
	String value() default "";
}

@Controller – is used to indicate a component at presentation layer.

@Service – is used to indicate a component at service layer and

@Repository – is used to indicate a component at persistence layer.

So, it all about semantics and alias. There is no any difference in functionality at all.

21. What are the advantages of Spring MVC over Struts MVC ?

As Spring MVC is state-or-the-art, it has many advantages over Struts:

  • Spring MVC has out-of-the box support for dependency injection, while Struts does not have it.
  • Spring MVC is non-intrusive, while Struts forces us to extend and implement it’s APIs.
  • Spring MVC is totally interface derived, while struts uses concrete implementations in many cases. For example: Action and Form objects.
  • Because of this, it is easier to test Spring MVC application than a Struts application.

22. How would you relate Spring MVC Framework to 3-tier architecture?

We will approach this in two parts:

  1. How Spring Framework helps us implement 3-tier architecture and then
  2. What part is specific to Spring MVC only.

3-tier architecture consists of:

  1. Presentation Layer
  2. Business Layer
  3. Persistence Layer

Earlier, presentation and business layer both resided at server side. But in today’s time, things are moving towards browser.

Here is typical layer composition in today’s modern web application:

Presentation layer:

  1. Providing the View of the application (Browser)
  2. Ability to handle Model to represent and transfer data to Business Layer, among others.
  3. Routing of client requests and
  4. Providing handlers to handle client requests( Think @Controller) – Server Side.
  5. Sending @Model objects back to client. – Server Side.

Business layer:

  1. Providing application workflows
  2. Providing service layer to assist Controllers( Think @Service), among others.

Persistence layer :

  1. Providing repository layer( Think @Repository, @Entity) and
  2. Database itself, among others.

As you can see clearly, Spring MVC manages Presentation Layer of it. Some part of it resides as static resources on browser while other part is on server.

Note: Spring MVC Interview Questions 19,20,21 are generic in nature and not so frequent to be asked in an interview.

23. What is Spring MVC Interceptor and how to use it?

Interceptors are used to:

  1. Intercept the HTTP request URL for which they are configured and
  2. To execute some logic at specific points in the HTTP request life-cycle.

Interceptors works like Servlet filters (If you remember!).

To implement Interceptors, we use HandlerInterceptor or HandlerInterceptorAdaptor and then override one or more methods of these to hook our logic.

Methods provided by an interceptor are:

  1. public boolean preHandle(HTTPServletRequest, HTTPServletResponse, Object handler) – Executed before a request is served.
  2. public void postHandle(HTTPServletRequest, HTTPServletResponse, Object handler, ModelAndView modelAndView) – Executed after a request is served but before view is rendered.
  3. public void afterCompletion(HTTPServletRequest, HTTPServletResponse, Object handler, Exception ex) – Executed after view is rendered and request is complete.

24. What are the minimum configurations needed to create Spring MVC application?

Here are the minimum things which are required to start with a MVC application:

  1. Create a project and add the dependencies: spring-context.jar, spring-mvc.jar
  2. In web.xml, configure DispatcherServlet.
  3. Configure Controller class(es) and add the Request mappings. Can be done via. XML, annotation or java based configuration.
  4. Configure View resolver.
  5. Configure required beans.

25. What is ContextLoaderListener in Spring MVC?

Note: Thought to be simple bit one of the most complex Spring MVC Interview Questions to put in words exactly. So, PAY ATTENTION.

ContextLoaderListener is Spring class which listenes to the ServletContext creation and loads the RootWebApplicationContext into it.

This RootWebApplicationContext can then work as most parent application context, holding beans which have application wide concerns like repositories.

After this, one or more DispatcherServlet gets register with ServletContext. Configuration for each DispatcherServlet, like Controller, ViewResolver, is typically given in dispatcherservletname-servlet.xml.

From this XMLs, Spring creates DispatcherServlet specific child contexts.

At this time, these child contexts can use the beans available through WebApplicationRootContext.

26. Explain Model, ModelMap, ModelAndView of Spring MVC.

Model is the data holder class which is required by View to render it to the user in a typical scenario.

ModelMap is a collection of Model objects. It’s a LinkedHashMap behind the scene.

Generally, we set the Model attributes in Controller methods and then return the view name only.

With ModelAndView, we can return both Model and View at same time.

27. Explain @ModelAttribute.

At method level, @ModelAttribute is used to set the Model object fields.

For example:

@Model
public class Employee {
    private String name;
    private String address;

    //other fields

    //getters and setters
}
@Controller
public class EmployeeController{
    //    ...
    @ModelAttribute("Employee")
    public Employee fillEmployee() {
        Employee emp = new Employee();
        emp.setName("Emp1");
        emp.setAddress("Emp1 Address");
        return emp;
    }
}

At method parameter level, it is used to get the Model data like below:

@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String add(@ModelAttribute("employee") Employee employee) {
}

28. Explain @SessionAttribute and @SessionAttributes.

@SessionAttributes is used at class level to set Model object(s) in user session.

@Model
public class Employee {
    private String name;
    private String address;

    //other fields

    //getters and setters
}
@Controller
@SessionAttributes("employee")
public class EmployeeController{

    @RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
    public String add(@ModelAttribute("employee") Employee employee) {
    //method code
    }

}

With the help of above code, employee object will be added to the user session.

If we want to get the Model object(s) from user session, we can use @SessionAttribute as below:

@Controller
@SessionAttributes("employee")
public class EmployeeController{

    @RequestMapping(value = "/manipulateEmp")
    public String manipulate(@SessionAttribute("employee") Employee employee) {
    //method code
    }

}

29. How to validate form data in Spring Web MVC Framework?

Validation in Spring MVC can be done in two ways:

  1. By using any JSR-303 compliant implementation or
  2. By creating your own Validator by implementing Spring Validator interface.

30. What is a Form backing object?

When we submit the form, the form data is sent from the View to the Controller.

This form data is composed in some form backing object and then received typically as @RequestBody in the Controller.

So, It is just a container class for the form-data we submit through filling out the form.

31. What is a @InitBinder annotation?

It is a method level annotation used in a Controller to manipulate form backing object, HTTP request etc.

By using @InitBinder, we can attach components like Validators, Formatters or PropertyEditors to the coming HTTP request.

32. What is BindingResult?

BindingResult is the container class for all the errors coming from Validator.

First, Spring Validates the form through Validator.

If there are any validation errors, Spring put them in BindingResult object and attach it to the View.

33. What is ViewResolver in Spring MVC?

ViewResolver is a Spring MVC component.

It takes a view name as input and return a view page as output. The view page then renders the Model object, if applicable.

By doing this, Spring is decoupling the View technology from the Controller logic that is composing the Model object.

34. Which ViewResolver class is widely used?

InternalResourceViewResolver, an implementation of ViewResolver is a commonly used view resolver.

We provide:

  1. Directory location of the view pages. e.g. /WEB-INF/staticpages
  2. and View page suffix. e.g. .html

to the ViewResolver at the time of configuring it.

It then selects the view page from the view name with the help of this configuration.

For example:

By providing the view name employeprofile, ViewResolver will select the page: /WEB-INF/staticemployeprofile.html

35. What is a MultipartResolver in Spring MVC?

Multipart Resolver is used to support the file uploading in a Spring MVC application.

When a Html Form request reaches to DispatcherServlet, it forwards it to the bean defined in the metadata with id multipartResolver.

This resolver then sends the MultipartHttpServletRequest to the controller method where we can handle the file operations.

Spring provides us two implementations of MultipartResolver:

  1. CommonsMultipartResolver (Support for Apache commons fileupload)
  2. StandardServletMultipartResolver (Support for Servlet 3 API)

36. How to upload a file in Spring MVC application?

First, in the view, we will have to declare the enctype attribute of <form> tag like below:

<form method="POST" action="uploadFile" enctype="multipart/form-data">
//Form items
</form>

When user clicks on the form’s submit button, it will go to the dispatcher servlet.

Dispatcher Servlet will then forward it to a multipart resolver. We can configure this multipart resolver as:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <beans:property name="maxUploadSize" value="100000" />
</bean>

Now, we can just create a method in the Controller to handle this upload request.

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadFileHandler(@RequestParam("file") MultipartFile file) {
//file handling logic 
//e.g. file.getBytes() and then put it in some output stream to save it on //server.
}

For this to work, we must have apache commons-fileupload in the classpath.

37. How to achieve localization in a Spring MVC application?

To support localization in our Spring MVC application, we will require to configure as below:

  1. Have different resource bundles for different locales e.g. messages.properties, messages_fr.properties
  2. Add ResourceBundleMessageSource for these messages.
  3. Add a Locale Resolver e.g. SessionLocaleResolver, CookieLocaleREsolver to resolve the locale.
  4. Register a LocalChangeInterceptor in the metadata.

38. How can we use Spring MVC to create Restful Web Service returning JSON response?

We can do this with the help of message converter. This message convert will transform the Model object to a JSON object.

We can create a message converter like below:

<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>

and then add it in the list of message handlers of RequestMappingHandler:

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonMessageConverter"/>
        </list>
    </property>
</bean>

To do this, we need to add jackson-databind in project’s dependency list and use the @ResponseBody or @RestController annotation in the controller.

39. Can we send an Object as the response of a Controller’s handler method?

Yes, with the help of @ResponseBody and @RestController.

40. How to handle exception in Spring MVC framework?

We can do it in 3 ways:

  1. If we want to handle some generic exception which might occur anywhere in the web application, we can define an Exception Resolver in the web application context.

For example:

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <prop key="path.to.your.CustomException">
                path/to/viewpage
            </prop>
        </props>
    </property>
</bean>

2. We can have @ExceptionHandler annotated methods in a @Controller, to handle exceptions occurring within scope of a Controller.

3. We can do the above across controllers by defining @ControllerAdvice class and adding @ExceptionHandler annotated methods into it.

With this we are finished with our whole list of interview questions on Spring MVC. Hope, this has helped you build your confidence for the interview.

What to read next?

Go for Spring AOP interview questions or Spring Boot interview questions.

or checkout our series on Spring Interview Questions and pick the topic which is suitable for you. Good Luck!!

Leave a Comment