Spring MVC Interview Questions

1). What is the Spring MVC framework?

The Spring web MVC framework provides MVC architecture (model-view-controller) and readymade components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between model, view, and controller parts of the application.

Spring framework provides lots of advantages over other MVC frameworks e.g.

Clear separation of roles – controller, validator, command object, form object, model object, DispatcherServlet, handler mapping, view resolver, etc. Each role can be fulfilled by a specialized object. Powerful and straightforward configuration options of both framework and application classes as JavaBeans. Reusable business code – no need for duplication. You can use existing business objects as command or form objects instead of mirroring them in order to extend a particular framework base class. Customizable binding and validation Customizable handler mapping and view resolution Customizable locale and theme resolution

A JSP form tag library (FTL), introduced in Spring 2.0, that makes writing forms in JSP pages much easier. etc.

2). What Does the @ExceptionHandler Annotation Do?

The @ExceptionHandler annotation allows us to define a method that will handle the exceptions. We may use the annotation independently, but it's a far better option to use it together with the @ControllerAdvice. Thus, we can set up a global error handling mechanism. In this way, we don't need to write the code for the exception handling within every controller.

3). What is the front controller class of Spring MVC?

A front controller is defined as “a controller which handles all requests for a Web Application.” DispatcherServlet (actually a servlet) is the front controller in Spring MVC that intercepts every request and then dispatches/forwards requests to an appropriate controller.

When a web request is sent to a Spring MVC application, the dispatcher servlet first receives the request. Then it organizes the different components configured in Spring’s web application context (e.g. actual request handler controller and view resolvers) or annotations present in the controller itself, all needed to handle the request.

4). How can we use Spring to create Rest Web Service returning JSON response?

We can use the Comtorller or Restcontroller for that.


 @Controller
public class EmployeeRESTController
{
    @RequestMapping(value = "/employees")
    public @ResponseBody EmployeeListVO getAllEmployees()
    {
        EmployeeListVO employees = new EmployeeListVO();
        //Add employees
        return employees;
    }
}

Alternatively, you can use @RestController annotation in place of @Controller annotation. This will remove the need to using @ResponseBody.

So you can write the above controller as below.


 @RestController
public class EmployeeRESTController
{
    @RequestMapping(value = "/employees")
    public EmployeeListVO getAllEmployees()
    {
        EmployeeListVO employees = new EmployeeListVO();
        //Add employees
        return employees;
    }
}

@RestController = @Controller + @ResponseBody

So you can write the above controller as below.


 @RestController
public class EmployeeRESTController
{
    @RequestMapping(value = "/employees")
    public EmployeeListVO getAllEmployees()
    {
        EmployeeListVO employees = new EmployeeListVO();
        //Add employees
        return employees;
    }
}

for JSON response, we need to add Jackson databaind com.fasterxml.jackson.core :jackson-databind:2.4.1

5). What are the advantages of the Spring MVC Framework?

The following are the advantages of Spring MVC Framework : -

Separate roles - The Spring MVC separates the application into three interconnected layers where each layer has its role.

Light-weight - It uses light-weight servlet container to develop and deploy your application.

Powerful Configuration - It provides a robust configuration for both framework and application classes that includes easy referencing across contexts, such as from web controllers to business objects and validators.

Rapid development - The Spring MVC facilitates fast and parallel development. Reusable business code - Instead of creating new objects, it allows us to use the existing business objects. Flexible Mapping - It provides the specific annotations that easily redirect the page.

6). What Is a MultipartResolver and When Should We Use It?

The Spring framework provides one MultipartResolver implementation for use with Commons FileUpload and another for use with Servlet 3.0 multipart request parsing.

MultipartResolver from the org.springframework.web.multipart package is a strategy for parsing multipart requests including file uploads. There is one implementation based on Commons FileUpload and another based on Servlet 3.0 multipart request parsing.

To enable multipart handling, you need to declare a MultipartResolver bean in your DispatcherServlet Spring configuration with the name of multipartResolver. The DispatcherServlet detects it and applies it to the incoming request. When a POST with content-type of multipart/form-data is received, the resolver parses the content and wraps the current HttpServletRequest as MultipartHttpServletRequest to provide access to resolved parts in addition to exposing them as request parameters.

Servlet 3.0 Servlet 3.0 multipart parsing needs to be enabled through a Servlet container configuration. To do so:

In Java, set a MultipartConfigElement on the Servlet registration.

In web.xml, add a "" section to the servlet declaration.

The following example shows how to set a MultipartConfigElement on the Servlet registration: public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {


 // ...

    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {

        // Optionally also set maxFileSize, maxRequestSize, fileSizeThreshold
        registration.setMultipartConfig(new MultipartConfigElement("/tmp"));
    }

}

for more details about MultipartResolver,please refer to this tutorial.

7). Difference between &lt context:annotation-config &gt vs &ltcontext:component-scan&gt?

First difference between both tags is that context:annotation-config="" is used to activate applied annotations in already registered beans in application context. context:a>

It does'nt matter whether bean was registered by which mechanism e.g. using context:component-scan or it was defined in application-context.xml file itself. context:component-scan

Second difference is driven from first difference itself. It registers the beans defined in config file into context + it also scans the annotations inside beans and activates them.

So context:component-scan> does what context:annotation-config> does, but additionally it scan the packages and register the beans in application context /context:annotation-config> context:component-scan

8). Difference between @Component, @Controller, @Repository & @Service annotations?

The @Component annotation marks a java class as a bean so the component-scanning mechanism of spring can pick it up and pull it into the application context. To use this annotation, apply it over the class as below: @Component


 public class EmployeeDAOImpl implements EmployeeDAO {
    ...
}

The @Repository annotation is a special version of the @Component annotation with similar use and functionality.

In addition to importing the DAOs into the DI container, it also makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException.

The @Service annotation is also a specialization of the Component annotation. It doesn’t currently provide any additional behavior over the @Component annotation, but it’s a good idea to use @Service over @Component in service-layer classes because it specifies intent better.

@Controller annotation marks a class as a Spring Web MVC controller. It means @Component specialization, so beans marked with it are automatically imported into the DI container. When you add the @Controller annotation to a class, you can use another annotation i.e. @RequestMapping; to map URLs to instance methods of a class.

9). How will you Handle Exception in spring MVC?

We can Handle Exception in Spring MVC in 3 ways:

1) per exception 2) per controller 3) globally

If an unhandled exception is thrown during web request processing, the server will return an HTTP 500 response. To prevent this, we should annotate any of our custom exceptions with the @ResponseStatus annotation. This kind of exception is resolved by HandlerExceptionResolver.

This will cause the server to return an appropriate HTTP response with the specified status code when a controller method throws our exception. We should keep in mind that we shouldn't handle our exception somewhere else for this approach to work.

Another way to handle the exceptions is by using the @ExceptionHandler annotation. We add @ExceptionHandler methods to any controller and use them to handle the exceptions thrown from inside that controller. These methods can handle exceptions without the @ResponseStatus annotation, redirect the user to a dedicated error view, or build a totally custom error response.

We can also pass in the servlet-related objects (HttpServletRequest, HttpServletResponse, HttpSession, and Principal) as the parameters of the handler methods. But, we should remember that we can't put the Model object as the parameter directly.

The third option for handling errors is by @ControllerAdvice classes. It'll allow us to apply the same techniques, only this time at the application level and not only to the particular controller. To enable this, we need to use the @ControllerAdvice and the @ExceptionHandler together. This way exception handlers will handle exceptions thrown by any controller.

For more details please read the article Exception handling in Spring

10). What is an Init Binder?

A method annotated with @InitBinder is used to customize a request parameter, URI template, and backing/command objects

@Controller or @ControllerAdvice classes can have @InitBinder methods that initialize instances of WebDataBinder, and those, in turn, can:

Bind request parameters (that is, form or query data) to a model object.

Convert String-based request values (such as request parameters, path variables, headers, cookies, and others) to the target ty

pe of controller method arguments.

Format model object values as String values when rendering HTML forms.

@InitBinder methods can register controller-specific java.bean.PropertyEditor or Spring Converter and Formatter components. In addition, you can use the MVC config to register Converter and Formatter types in a globally shared FormattingConversionService.

@InitBinder methods support many of the same arguments that @RequestMapping methods do, except for @ModelAttribute (command object) arguments. Typically, they are declared with a WebDataBinder argument (for registrations) and a void return value. The following listing shows an example:


   @Controller
public class FormController {

    @InitBinder 
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

    // ...
}

11). What are the ways of reading data from the form in Spring MVC?

We can read the data from the form in Spring using 3 ways

1) HttpServletRequest interface - The HttpServletRequest is a java interface present in javax.servlet.http package. Like Servlets, you can use HttpServletRequest in Spring to read the HTML form data provided by the user.

2) @RequestParam annotation - The @RequestParam annotation reads the form data and binds it automatically to the parameter present in the provided method.

3) @ModelAttribute annotation - The @ModelAttribute annotation binds a method parameter or its return value to a named model attribute.

12). What is the use of BindingResult in Spring MVC validations?

The BindingResult is an interface that contains the information of validations. For example:-

For access to errors from validation and data binding for a command object (that is, a @ModelAttribute argument) or errors from the validation of a @RequestBody or @RequestPart arguments. You must declare an Errors, or BindingResult argument immediately after the validated method argument.


   @Controller
@SessionAttributes("pet") 
public class EditPetForm {

    // ...

    @PostMapping("/pets/{id}")
    public String handle(Pet pet, BindingResult errors, SessionStatus status) {
        if (errors.hasErrors) {
            // ...
        }
            status.setComplete(); 
            // ...
        }
    }
}

13). How will you validate user's input within a number range in Spring MVC?

We can validate the user's input within a number range by using the following annotations: -

@Min annotation - It is required to pass an integer value with @Min annotation. The user input must be equal to or greater than this value.

@Max annotation - It is required to pass an integer value with @Max annotation. The user input must be equal to or smaller than this value. eg.


     
import javax.validation.constraints.Max;  
import javax.validation.constraints.Min;  
import javax.validation.constraints.Size;  
  
public class Student {  
  
   @Size(min=1,message="required") 
    private String firstName;  
  
   @Size(min=1,message="required") 
    private String lastName;
  
    
    @Min(value=5, message="must be equal or greater than 5")  
    @Max(value=6, message="must be equal or less than 6")  
    private int age;  
  
    @RequestMapping("/save")  
    public String submitForm( @Valid @ModelAttribute("student") Student e, BindingResult br)  
    {  
        if(br.hasErrors())  
        {  
            return "viewpage";  
        }  
        else  
        {  //save student data
        return "success";  
        }  
    } 

For more details please read the article validation error handling in Spring

14). What Is the Role of the @Qualifier Annotation?

The @Qualifier annotation is used to resolve the autowiring conflict when there are multiple beans of the same type.

The @Qualifier annotation can be used on any class annotated with @Component or on methods annotated with @Bean. This annotation can also be applied on constructor arguments or method parameters.

or can use @Qualifier along with @Autowired. In fact spring will ask you explicitly select the bean if ambiguous bean type is found, in which case you should provide the qualifier

For Example in following case, it is necessary to provide a qualifier.


 @Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


 @Component
public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

If you are using field or setter injection then you have to place the @Autowired and @Qualifier on top of the field or setter function like below(any one of them will work)


 public Payroll {
   @Autowired @Qualifier("employee") private final Person person;
}

or


 public Payroll {
   private final Person person;
   @Autowired
   @Qualifier("employee")
   public void setPerson(Person person) {
     this.person = person;
   } 
}

If you are using constructor injection then the annotations should be placed on the constructor, else the code would not work. Use it like below -


 public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}
  

for quick remember we say that @Autowired to autowire(or search) by-type @Qualifier to autowire(or search) by-name

For more details please read the article validation error handling in Spring

15).

What does the ViewResolver class?

ViewResolver is an interface to be implemented by objects that can resolve views by name. There are many ways in which you can resolve view names.

These ways are supported by various in-built implementations of this interface. Most commonly used implementation is InternalResourceViewResolver class. It defines prefix and suffix properties to resolve the view component.

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

The servlet filters can pre-handle and post-handle every web request they serve — before and after it’s handled by that servlet. In Spring, HandlerInterceptor interface in your spring MVC application to pre-handle and post-handle web requests that are handled by Spring MVC controllers.

These handlers are mostly used to manipulate the model attributes returned/submitted they are passed to the views/controllers.

A handler interceptor can be registered for particular URL mappings, so it only intercepts requests mapped to certain URLs. Each handler interceptor must implement the HandlerInterceptor interface, which contains three callback methods for you to implement: preHandle(), postHandle() and afterCompletion().

Problem with a HandlerInterceptor interface is that your new class will have to implement all three methods irrespective of whether it is needed or not. To avoid overriding, you can use a HandlerInterceptorAdapter class. This class implements HandlerInterceptor and provides default blank implementations.

For more details please read the article view resolver example in Spring MVC

17). Explain a Controller Advice.

The @ControllerAdvice annotation allows us to write global code applicable to a wide range of controllers. We can tie the range of controllers to a chosen package or a specific annotation.

By default, @ControllerAdvice applies to the classes annotated with @Controller (or @RestController). We also have a few properties that we use if we want to be more specific.

If we want to restrict applicable classes to a package, we should add the name of the package to the annotation:


 @ControllerAdvice("my.package")
@ControllerAdvice(value = "my.package")
@ControllerAdvice(basePackages = "my.package")
It's also possible to use multiple packages, but this time we need to use an array instead of the String.

Besides restricting to the package by its name, we can do it by using one of the classes or interfaces from that package:

@ControllerAdvice(basePackageClasses = MyClass.class)

we should use it along with @ExceptionHandler. This combination will enable us to configure a global and more specific error handling mechanism without the need to implement it every time for every controller class.

18). Name the annotations used to handle different types of incoming HTTP request methods?

The following annotations are used to handle different types of incoming HTTP request methods: -

@GetMapping
 @PostMapping
 @PutMapping 
@PatchMapping
 @DeleteMapping

for more Annotation please read the article Spring MVC Annotations