Spring MVC Interview Questions with Answers

Spring MVC Interview Questions

Read other articles of this series

This post is the part of our Interview Questions series and in this post, we will discuss some commonly asked Spring MVC interview questions during a job interview.

Q1. What is a Controller in Spring MVC?

Controllers control the flow of the application execution. In Spring MVC architecture the DispatcherServlet works as Front Controller. DispatcherServlet process the request and pass the request to the controller class annotated with @Controller. Each controller class is responsible to handle one or more requests of a certain type.

For more detail, read Introduction to Spring Controllers

 

Q2. How to get ServletContext and ServletConfig in a Spring Bean?

There are two options for getting ServletContext and ServletConfig in a Spring Bean.

  • Use @Autowired annotation to inject ServletContext and ServletConfig in Spring Bean.
  • Implement Spring aware interfaces in the class that depends on ServletConfigor ServletContext

Using @Autowired annotation

@Autowired
ServletContext servletContext;
@Autowired
ServletConfig servletConfig;

Implementing Spring aware interfaces

public class ServletConfigAwareClass implements ServletConfigAware {

 private ServletConfig config;

 public void setServletConfig(ServletConfig servletConfig) {
  this.config = servletConfig;
 }

For more details, see ServletConfigAware

 

Q3. Explain the working of @RequestMapping?

The @RequestMapping is used to map web request to the controller in Spring MVC application. We can apply the @RequestMapping annotation to class-level and/or method-level in a controller.

 

Q4. What is ViewResolver in Spring?

The ViewResolver let SPring MVC application to render models in a browser without binding to a specific view technology (e.g. JSP  or Thymeleaf). This works by providing a mapping between view names and actual views.View addresses the preparation of data before handing over to a specific view technology.

 

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

Interceptors are useful to intercept the client request and process it. There are three options to intercept client request using Spring interceptors.

  • preHandle
  • postHandle
  • afterComplete (after the view is rendered to the client)

Interceptors are useful for cross-cutting concerns and help us avoid duplicate code (e.g. logging, profiling etc.).We can create spring interceptor by implementing a HandlerInterceptor interface or by extending the abstract class HandlerInterceptorAdapter.

 

Q6. How to handle exceptions in Spring MVC?

Spring MVC provides the following three options for exception handling

  1. @ExceptionHandler Annotation – ExceptionHandler is a Spring annotation handle exceptions thrown by request handling. This annotation works at the @Controller level.
  2. <em><strong>@ControllerAdvice</strong></em> Annotation – This annotation supports global Exception handler mechanism. A controller advice allows you to use exactly the same exception handling techniques but applies them across the application, not just to an individual controller.
  3. HandlerExceptionResolver – Resolve any exception thrown by the application.

For more information please read

 

Q7. How to validate form data in Spring Web MVC?

Spring provides built-in support to use JSR-303 based bean validation. For using JSR-303 based validation, we need to annotate bean variables with the required validations. Let’s take a simple example to validate customer object

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class Customer {

 @NotNull
 @Size(min = 2, max = 30)
 private String name;

 @NotNull
 @Min(18)
 private Integer age;

 //getter and setters

}

To trigger JSR-303 based validation, we only need to annotate our incoming object with a @Validannotation

@Controller
public class WebController {

 @PostMapping("/")
 public String checkPersonInfo(@Valid Customer customer, BindingResult bindingResult) {

  if (bindingResult.hasErrors()) {
   return "form";
  }

  return "redirect:/results";
 }
}

Spring validation also provides an interface that can create custom validators (in a case out of the box validator does not satisfy the requirements.)

 

Q8. What is MultipartResolver? When should we use this?

We use this interface to upload files. Spring Framework provides two implementations for this interface

  • CommonsMultipartResolver – For Apache Commons FileUpload.
  • StandardServletMultipartResolver – For the Servlet 3.0+ Part API

We can use either one of this to implement file upload feature in our application.

 

Q9. What is DispatcherServlet?

DispatcherServlet is the Spring MVC implementation of the front controller pattern. This is the central entry point in the Spring MVC application or HTTP request handlers/controllers. It’s a servlet that takes the incoming request, and delegates processing of that request to one of several handlers, the mapping of which is specified in the DispatcherServlet configuration.

front controller

 

Q10. How to upload a file in Spring MVC Application?

Spring Boot provides “CommonsMultipartResolver” and “StandardServletMultipartResolver” as two standard ways to upload a file. To upload a file using “CommonsMultipartResolver”, we need to add the commons-fileupload.jar and commons-io.jar dependencies

<!-- Apache Commons Upload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.2.2</version>
</dependency>
 
<!-- Apache Commons Upload -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.3.2</version>
</dependency>

Finally, you need to write a controller to accept incoming file and store data accordingly. Method parameter should have MultipartFile as one parameter. Here is how your code look like

@Controller
@RequestMapping("/upload")
public class UploadController {

 @ResponseBody
 public String handleUpload(
  @RequestParam(value = "file", required = false) MultipartFile multipartFile,
  HttpServletResponse httpServletResponse) {

  String orgName = multipartFile.getOriginalFilename();

  //file saving logic
 }

Read our article Uploading A Files with Spring MVC in-depth tutorials.

 

Q11. How to enable localization support in Spring MVC?

Spring framework provides LocalResolver to handle internationalization and localization. To enable support for the localization in your application, we need to register below two beans.

  • SessionLocaleResolver: LocaleResolver implementation that uses a locale attribute in the user’s session in case of a custom setting, with a fallback to the specified default locale or the request’s accept-header locale.
  • LocaleChangeInterceptor : Interceptor that allows for changing the current locale on every request, via a configurable request parameter (default parameter name: “locale”).
@Bean
public LocaleResolver localeResolver(){
       SessionLocaleResolver localeResolver = new SessionLocaleResolver();
       localeResolver.setDefaultLocale(Locale.US);
       return  localeResolver;
   }
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
    LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
    localeChangeInterceptor.setParamName("language");
    return localeChangeInterceptor;
}

For detail, read Internationalization in Spring Boot

 

Q12. What is ContextLoaderListner in Spring MVC and what is the use of this?

The ContextLoaderListener is the root application context. Below are the main uses of the ContextLoaderListener.

  • It helps to bind the ApplicationContext and ServletContext lifecycle.
  • It helps to create ApplicationContext automatically without the need of any additional code.
<listener>
  <listener-class>
    org.springframework.web.context.ContextLoaderListener
  </listener-class>
</listener>
  
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/spring/applicationContext.xml</param-value>
</context-param>

To use Java based configuration for your Spring MVC application, please read Spring WebApplicationInitializer

 

Q13. How to use JNDI DataSource in Spring Web Application?

There are multiple ways to use the JNDI datasource provided by Tomcat. We can use the Spring XML based configurations to get the datasource.

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
...
<jee:jndi-lookup id="dataSource"
   jndi-name="jdbc/Database"
   expected-type="javax.sql.DataSource" />

Another way (Preferred) is to configure the data source as a Spring Bean

<bean id="jndiDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/TestDB"/>
</bean>

The last option is to declare the JNDI configuration in the server.xml file and use it in the Tomcat’s context.xml.For more detail, please read JNDI Datasource HOW-TO

 

Q14. What is Viewresolver pattern in Spring MVC and how does it work?

View resolver is a J2EE design pattern which allows applications to dynamically choose a view technology. Spring provides view resolvers implementation to help passing information to the browser without binding to a specific view technology. In Spring MVC, control returns the name of the view which is passed to the view resolver in Spring MVC for choosing the right templating engine. The two interfaces important to the way Spring handles views are ViewResolver and View.

 

Q15. What is the scope of Spring Controller?

Spring MVC controllers are singleton by default. Please note it will share any object created in the controller across all requests.

 

Q16. What is the role of @EnableWebMvc annotation in Spring MVC?

The @EnableWebMvc annotation allows you to configure Spring application without using the XML based configuration/declaration. This annotation is equivalent to using the <mvc:annotation-driven /> in XML. Here is the list of some important features of the @EnableWebMvc annotation:

  • Enable support for request processing.
  • Support for validation using JSR-303 bean validation.
  • Number and date formatting support.
  • HttpMessageConverter support.

For more detail, please refer to Spring documentation.

 

Q17. When to use the @ResponseBody annotation in Spring MVC?

The @ResponseBody annotation allows you to return the response directly in the HTTP response body. We can use this annotation when we do not want to send/place the response into the Model or view name is not needed.

The @ResponseBody annotation is useful while working on the REST services in Spring MVC where we want to write the response directly into the HTTP response. Here is an example for using this annotation:

@ResponseBody
  @RequestMapping(path = "/product", method = RequestMethod.GET)
  public Product getProducts(
  @RequestParam(value = "code") String code) {
  return productService.getProductByCode(code);
 }

 

Q18. Explain the PathVariable

Annotation which shows that a method parameter should be bound to a URI template variable. Supported for RequestMapping annotated handler methods. Let’s take an example where we want to get order detail based on the order id and our URL looks like:

test.javadevjournal.com/orders/abc123/

To get the order id from the URL using path variable, our code looks like:

@RequestMapping(value = "/orders/{orderId}", method=RequestMethod.GET)
public String getOrder(@PathVariable String orderId){
//fetch order
}

It allows to have multiple @PathVariable annotation in the same definition or we can use a map to accept all variables. We can use any of the way to use multiple @PathVariable annotation.

@RequestMapping(value = "/webshop/{shopId}/orders/{orderId}", method=RequestMethod.GET)
public String getOrder(@PathVariable String shopId,@PathVariable String orderId){
//fetch order
}
// alternate
@RequestMapping(value = "/webshop/{shopId}/orders/{orderId}", method=RequestMethod.GET)
public String getOrder(@PathVariable Map<String,String> reqMap){
//fetch order
}

 

Q19. What is the difference between @Controller and @RestController?

There are few differences between @Controller and @RestController annotation:

  1. @Controller annotation marks a class as Spring MVC Controller while the @RestController is a convenience annotation which also adds both @Controller and @ResponseBody annotation together.
  2. @RestController automatically converts the response to JSON/XML.
  3. The @RestController annotation cannot return a view while @Controller can do that.

Here is a definition to both for better clarity:

@Controller
public class ControllerExample{

  @RequestMapping(value={"/uri"})
  @ResponseBody
  public CustomResponse method(){
      //return response
   }
}
@RestController
public class ControllerExample{

  @RequestMapping(value={"/uri"})
  public CustomResponse method(){
      //return response
   }
}

 

Q20. Explain Model Attribute

This is one of the most important and commonly used annotation in Spring MVC.The @ModelAttribute annotation that binds a method parameter or method return value to a named model attribute, exposed to a web view.Spring MVC will invoke all methods with @ModelAttribute annotation before any handler method executed by the framework.

An @ModelAttribute on a method argument shows the argument should be retrieved from the model. If not present in the model, the argument should be instantiated first and then added to the model.We can use @ModelAttribute annotation at method and method parameter level.Read our article Spring MVC @ModelAttribute Annotation  for more detail.

 

In this article, we discussed some commonly asked Spring MVC interview questions during a job interview. Please read  Spring Interview Questions for the list of Spring core questions.

Comments are closed.

Scroll to Top