Google News
logo
Java Spring MVC Interview Questions
The Spring web MVC framework facilitates model-view-controller (MVC) architecture and ready components that can be used to develop flexible and loosely coupled web applications.
 
The MVC pattern separates the different aspects of an application (for example, input logic, business logic, and UI logic) and also enables loose coupling between model, view and controller within the application.
The front controller is a DispatcherServlet class present in org.springframework.web.servlet package. It dispatches the request to the appropriate controller and manages the flow of the application. It is required to specify the DispatcherServlet class in the web.xml file.
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.
Spring MVC implements a clear separation of concerns that allows us to develop and unit test our applications easily.
 
The concepts like :
 
* Dispatcher Servlet
* Controllers
* View Resolvers
* Views, Models
* ModelAndView
* Model and Session Attributes

are completely independent of each other, and they are responsible for one thing only.
 
Therefore, MVC gives us quite big flexibility. It's based on interfaces (with provided implementation classes), and we can configure every part of the framework by using custom interfaces.
 
Another important thing is that we aren't tied to a specific view technology (for example, JSP), but we have the option to choose from the ones we like the most.
 
Also, we don't use Spring MVC only in web applications development but in the creation of RESTful web services as well.
The Spring MVC application contains an additional configuration file that contains the properties information. This file can be created either in the form of an xml file or properties file. In this file, we generally define the base-package and view resolver where DispatcherServlet searches for the controller classes and view components path. However, it can also contain various other configuration properties.
The InternalResourceViewResolver is a class which is used to resolve internal view in Spring MVC. Here, you can define the properties like prefix and suffix where prefix contains the location of view page and suffix contains the extension of view page.
 
For example :
 
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/jsp/"></property>  
        <property name="suffix" value=".jsp"></property>          
</bean>

 

The Model interface defines a holder for model attributes. The ModelMap has a similar purpose, with the ability to pass a collection of values. It then treats those values as if they were within a Map. We should note that in Model (ModelMap) we can only store data. We put data in and return a view name.
 
On the other hand, with the ModelAndView, we return the object itself. We set all the required information, like the data and the view name, in the object we're returning.
* AOP module (Aspect Oriented Programming)
* JDBC abstraction and DAO module
* The Core container module
* MVC framework module
* Application context module
* O/R mapping integration module (Object/Relational)
* Web module
Spring MVC framework is request-driven and is designed around a central Servlet that handles all the HTTP requests and responses. The DispatcherServlet, however, does a lot more than just that. It seamlessly integrates with the IoC container and allows you to use each feature of Spring.

On receiving an HTTP request, the DispatcherServlet consults HandlerMapping (these are the configuration files) to call the appropriate Controller. Then, the controller calls appropriate service methods to set the Model data. It also returns the view name to DispatcherServlet. DispatcherServlet, with the help of ViewResolver, picks up the defined view for the request. Once the view is finalized, the DispatcherServlet passes the Model data to View – where it is finally rendered on the browser.
A front controller is a controller which handles all requests for a Web application. When it comes to Spring MVC, DispatcherServlet is that front controller. When a web request is sent to a Spring MVC application, the DIspatcherServlet takes care of everything. First, it takes the request. Then, it organizes the different components like request handlers, controllers, view resolvers, and such – all needed to handle the request. And finally, it renders the content on the browser.
Spring primarily supports two types of validations :
 
* Using JSR-303 Annotations and any reference implementation, for example, Hibernate Validator.

* Implementing org.springframework.validation.Validator interface.
Hibernate can be accessed in the following two ways :
 
* By IOC with a Callback and HibernateTemplate.

* By applying an AOP Interceptor and broadening the HibernateDaoSupport.
The @Controller annotation is used to declare a class as a controller class. It is required to specify this annotation on the class name. For example :
 
@Controller  
class Demo  
{  
  
}

 

The @RequestMapping annotation is used to map the controller class and its methods. You can specify this annotation on the class name as well as method name with a particular URL that represents the path of the requested page. For example :
 
@Controller   
@RequestMapping("/ form")  
  class Demo  
  {  
    @RequestMapping("/show")  
     public String display()  
     {  
  
     }  
 }

 

The following annotations are used to handle different types of incoming HTTP request methods :
 
*  @GetMapping
*  @PostMapping
*  @PutMapping
*  @PatchMapping
*  @DeleteMapping

It is used to read and parse the Spring configuration file and process the loading of beans in that configuration file.
 
Code Example :
 
<servlet>
    <servlet-name>Spring</servlet-name>
    <servlet-class>
        org.Springframework.web.servlet.DispatcherServlet
    </servlet-class>
      
     <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </init-param>
      
    <load-on-startup>1</load-on-startup>
</servlet>

 

The @PathVariable is an annotation that is used as a parameter in the handler method for extracting the value of the URI template.
 
Example :
@RequestMapping("/Login/{Lid}")
public String handleRequest(@PathVariable("Lid") String Login, Model map)
  {
}

 

The @RequestBody annotation is responsible for binding the HTTP body request to a domain object. The incoming HTTP request is automatically de-serialized to the Java object by Spring with the help of the HTTP message converters.
When the @ResponseBody annotation is used in the MVC controller, it indicates that the developer needs to write a return type of declared method directly to the HTTP response body. Here, invoking of the model is not required and the view name is not interpreted by Spring.
Interceptors play a handy role in Spring MVC. They are used to intercept the request from the client, process the request at different times like before handling the request, after handling the request and after completion of the presentation part i.e. view page, etc.
 
It is also used from cross-cutting concerns and reduces the code handler repetition like a modification of global parameters in the model later, logging, etc.
Yes, Spring allows to have multiple configuration files in one application.
 
There are mainly two ways to achieve this and those ways are mentioned below :
 
(i) The Developer has to declare all the files in the web.xml using the parameter :
 
<servlet>
        <servlet-name>Spring</servlet-name>
        <servlet-class>
            org.Springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                WEB-INF/Spring-dao-hibernate.xml,
           </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
</servlet>
     
<servlet-mapping>
        <servlet-name>Spring</servlet-name>
        <url-pattern>/</url-pattern>
</servlet-mapping>

 

(ii) The developer can import files into the existing configuration.
 
<beans>
    <import resource="Spring-dao-hibernate.xml"/>
</beans>

 

The ContextLoaderListener is a listener that helps to bootstrap Spring MVC. As the name suggests, it loads and creates the ApplicationContext, so you don't have to write explicit code to do create it.
 
The application context is where Spring bean leaves. For a web application, there is is a subclass called WebAppliationContext.
 
The ContextLoaderListener also ties the lifecycle of the ApplicationContext to the lifecycle of the  ServletContext. You can get the ServletContext from the WebApplicationContext using the getServletContext() method.
The @RequestParam is a Spring MVC annotation that is used to extract a request parameter or query parameters from the URL in the Controller's handler method as shown below : 
 
public String personDetail(@RequestParam("id") long id){
  ....
  return "personDetails";
}
 
The @RequestParam annotation also supports data type conversion, e.g. you can see here a String is converted to log automatically, but it can also result in an exception if query parameter is not present or in case of type mismatch. You can also make the parameter optional by using requried=false, e.g. @RequestParam  (value="id", required=false )
Spring MVC provides the following three options for exception handling :
 
* @ExceptionHandler Annotation : ExceptionHandler is a Spring annotation handle exceptions thrown by request handling. This annotation works at the @Controller level.

* <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.

* HandlerExceptionResolver : Resolve any exception thrown by the application.
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.
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;
}

 

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.
The Model Map is a class that provides the implementation of Map. It extends the LinkedIn Hash Map class. It eases to pass a collection of values as they were within a Map.
The following ways to read the data from the form are : 
 
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.

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

@ModelAttribute annotation : The @ModelAttribute annotation binds a method parameter or its return value to a named model attribute.
The Bean Validation API is a Java specification which is used to apply constraints on object model via annotations. Here, we can validate a length, number, regular expression, etc. Apart from that, we can also provide custom validations.
 
As Bean Validation API is just a specification, it requires an implementation. So, for that, it uses Hibernate Validator. The Hibernate Validator is a fully compliant JSR-303/309 implementation that allows to express and validate application constraints.
In Spring MVC Validation, 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.
The Spring provides integration support with apache tiles framework. So we can manage the layout of the Spring MVC application with the help of spring tiles support. The following are the advantages of Tiles support in Spring MVC :
 
* Reusability : We can reuse a single component in multiple pages like header and footer components.

* Centralized control : We can control the layout of the page by a single template page only.

* Easy to change the layout : By the help of a single template page, we can change the layout of the page anytime. So your website can easily adopt new technologies such as bootstrap and jQuery.
PreparedStatementCreator is one of the most commonly used interfaces for writing data to the database. createPreparedStatement() is a method that can be used to create and return PreparedStatement from the Connection argument, and exception handling is automatically taken care of. When this interface is implemented, a different interface SqlProvider can also be implemented which has a method called getSql(). This method is useful for providing sql strings to the JdbcTemplate. It does not handle SQLExceptions.
They are :
 
* ClassPathXmlApplicationContext
* FileSystemXmlApplicationContext
* XmlWebApplicationContext
AOP is an important part of Spring MVC Architecture. AOP is used for crosscutting concern and also for applications, validation of data, module logging, transaction management, authentication, and objects.
 
There are many parts of Aspect Oriented Programming. These are mentioned below :
 
* Aspect : Aspect is responsible for cross-cutting concerns like transaction management etc.

* Advice : It is basically an action and method that are executed and is also used for a specified join point.

* Pointcut : It is responsible for the execution of advice in terms of regular expressions.

* Joint Point : It is a point in the application for processes like exception handling, execution of the method, variable values change, etc.

* Advice Arguments : These arguments are used for passing of methods.
To handle views in Spring MVC, we need to configure InternalResourceViewResolver bean in spring XML where we need to define prefix and suffix of the views name.
 
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/pages/"/>
  <property name="suffix" value=".jsp"/> 
</bean>

 

Implementing HandlerInterceptor interface forces to implement all the three methods preHandle(), postHandle() and afterCompletion() irrespective of whether it is needed or not. To avoid that, you can use HandlerInterceptorAdapter class that implements HandlerInterceptor and provides default empty implementations. Extending HandlerInterceptorAdapter class allows you to override only the method that are required.