Spring MVC Interview Questions

Spring MVC Interview Questions
Spring MVC Interview Questions

Spring MVC Interview Questions

1. Explain Spring MVC Execution Flow

Screenshot2B2019 06 222Bat2B16.35.37

The DispatcherServlet is an actual Servlet and inherits from the HttpServlet base class. When a request is sent to the web application, the workflow of handling a request is as below:
• When DispatcherServlet receives the request, it dispatches the task of selecting an appropriate controller to HandlerMapping. Then, HandlerMapping selects the controller which is mapped to the incoming request URL and returns the (selected Handler) and Controller to DispatcherServlet.
• DispatcherServlet dispatches the task of executing the business logic by Controller to HandlerAdapter. HandlerAdapter calls the business logic process of Controller. When the HandlerAdapter calls the controller, Interceptor is invoked to intercept the request.
• Then, Controller executes the business logic and sets the processing result in Model. Then, if there is any Interceptor to intercept the response, is invoked as a post process. Then Controller returns the logical name of view to HandlerAdapter.
• DispatcherServlet dispatches the task of resolving the View corresponding to the View name to ViewResolver. ViewResolver returns the View mapped to View name.
• DispatcherServlet dispatches the rendering process to returned View.
• View renders Model data and returns the response

high level

2. How to Take attributes from Spring MVC form

Please make sure you have same name in form and in bean while taking the input from form.
1. @RequestParam

public ModelAndView addForm(@RequestParam("firstName") String fName, @RequestParam("lastName") String lName)

2. @ModelAttribute – Used to take the object from form

public ModelAndView addForm(@ModelAttribute("student1") StudentBean student1)

ModelAttribute can also e used for Common codewe can write in a single method which will be called before calling any other method like ininBinder () or the request mapping handler method.

3. How to do the form validation in Spring MVC?

1. Binding Result
Many time while submitting the form we face 404 error because of incorrect data binding or some exception occurred while converting the datatypes. To debug this issue we should have below changes.

1.1. Java– add org.springframework.validation.BindingResult object to the form submission method and add below line to it.

public ModelAndView addForm(@ModelAttribute("student1") StudentBean student1, BindingResult result){
/*BindingResult object will contain the error if the values are not converted from form to the object.*/
      if(result.hasErrors()){
        ModelAndView view = new ModelAndView("addForm"); 
        return view
      }
}

1.2  JSP – add below lines on jsp to display the errors

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<form:errors path=student1.*>

2. Inbuilt custom property editor
Define a method with @InitBinder with param WebDataBinder binder, in this method you can specify the custom / in built property editors for validation. We can have any name to the method, this method will be called before the submit method of the form.

@InitBinder
public void bindData(WebDataBinder binder){
 System.out.println("Entered in bindData");
 binder.setDisallowedFields(new String [] {"telephone"} ); // this will skip the internal validation part for tel
 SimpleDateFormat dateFormat = new SimpleDateFormat("yyy.dd.mm");
 binder.registerCustomEditor(Date.class,"dob", new CustomDateEditor(dateFormat, true)); // spring provide lots of custom editors
 // to customize the inbuilt datatypes, the 2nd param true defines - allow empty value
 System.out.println("Exited from bindData");
}

3. Adding validation annotation and message file on variables
Spring allows any validation vendor which implements the JSR-303 or JSR 314X specifications.
A. Add validation annotation in POJO

@Data
public class PersonForm {

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

    @NotNull
    @Min(18)
    private Integer age;
}

B. To work it add @Valid annotation as a parameter to the handler method.

public ModelAndView addForm(@Valid @ModelAttribute("student1") StudentBean student1, BindingResult result){

C. Add below entry in the Spring-dispatcher.xml to read the message.properties file.

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="/WEB-INF/messages">
    </property>
</bean>

D. Create messages.properties file in web-inf folder.
E. Spring will read the validation error messages like below hierarchy.

spring2Bvalidation

F. In order to make the error messages dynamic we can place {0} in the messages to take the dynamic values.
Size.student1.firstName={0} should have minimum {2} and maximum {1} characters.

4. What is DispatcherServlet and ContextLoaderListener?

Spring’s web MVC framework is, like many other web MVC frameworks, request-driven, designed around a central Servlet that handles all the HTTP requests and responses. Spring’s DispatcherServlet however, does more than just that. It is completely integrated with the Spring IoC container so it allows you to use every feature that Spring has.

After receiving an HTTP request, DispatcherServlet consults the HandlerMapping (configuration files) to call the appropriate Controller. The Controller takes the request and calls the appropriate service methods and set model data and then returns view name to the DispatcherServlet. The DispatcherServlet will take help from ViewResolver to pickup the defined view for the request. Once view is finalized, The DispatcherServlet passes the model data to the view which is finally rendered on the browser.

<web-app>
  <display-name>Archetype Created Web Application</display-name>
 
  <servlet>
        <servlet-name>spring</servlet-name>
            <servlet-class>
                org.springframework.web.servlet.DispatcherServlet
            </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
     
</web-app>

By default, DispatcherServlet loads its configuration file using <servlet_name>-servlet.xml. E.g. with above web.xml file, DispatcherServlet will try to find spring-servlet.xml file in classpath.

ContextLoaderListener reads the spring configuration file (with value given against “contextConfigLocation” in web.xml), parse it and loads the beans defined in that config file. e.g.

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

5. Can we have multiple Spring configuration files?

YES. You can have multiple spring context files. There are two ways to make spring read and configure them.
a) Specify all files in web.xml file using contextConfigLocation init 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,
                WEB-INF/spring-services.xml,
                WEB-INF/spring-security.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>

b) You can import them into existing configuration file you have already configured.

<beans>
    <import resource="spring-dao-hibernate.xml"/>
    <import resource="spring-services.xml"/>
    <import resource="spring-security.xml"/>
   
    ... //Other configuration stuff

</beans>

6. Difference between <context:annotation-config> vs <context:component-scan>?

1. First big difference between both tags is that <context:annotation-config> is used to activate applied annotations in already registered beans in application context. Note that it simply does not matter whether bean was registered by which mechanism e.g. using <context:component-scan> or it was defined in application-context.xml file itself.
2. 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 activate them. So <context:component-scan> does what <context:annotation-config> does, but additionally it scan the packages and register the beans in application context.

7. What are different View Resolvers available in Spring?

1. UrlBasedViewResolver
The UrlBasedViewResolver   provides the mapping logical view names and URLs directly that hands over to the view class specified. Javadoc for UrlBasedViewResolver mentions: “Note: When chaining ViewResolvers, a UrlBasedViewResolver always needs to be last, as it will attempt to resolve any view name, no matter whether the underlying resource actually exists.” It will resolve the controller based on the URL. For e.g. if below URL comes then :
http://localhost:8080/Rent/UrlBasedViewResolver
then it will search for the controller names UrlBasedViewResolver and execute the code written in protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)throws Exception {
method.

2. InternalResourceViewResolver
This ViewResolver allows us to set properties such as prefix or suffix to the view name to generate the final view page URL:

@Bean
public ViewResolver internalResourceViewResolver() {
    InternalResourceViewResolver bean = new InternalResourceViewResolver();
    bean.setViewClass(JstlView.class);
    bean.setPrefix("/WEB-INF/view/");
    bean.setSuffix(".jsp");
    return bean;
}

For such simplicity of the example, we don’t need a controller to process the request. We only need a simple jsp page, placed in the /WEB-INF/view folder

3. ResourceBundleViewResolver
As the name of this resolver suggest a ResourceBundleViewResolver uses bean definitions in a ResourceBundle. First, we add the ResourceBundleViewResolver to the previous configuration:

@Bean
public ViewResolver resourceBundleViewResolver() {
    ResourceBundleViewResolver bean = new ResourceBundleViewResolver();
    bean.setBasename("spring-views");
    return bean;
}

The bundle is typically defined in a properties file, located in the classpath(in resources folder). Below is the views.properties file:

sample.(class)=org.springframework.web.servlet.view.JstlView
sample.url=/WEB-INF/view/sample.jsp

4. XmlViewResolver
This implementation of ViewResolver accepts a configuration file written in XML with the same DTD as Spring’s XML bean factories:

@Bean
public ViewResolver xmlViewResolver() {
    XmlViewResolver bean = new XmlViewResolver();
    bean.setLocation(new ClassPathResource("views.xml"));
    return bean;
}

Below is the configuration file, views.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
    <bean id="xmlConfig" class="org.springframework.web.servlet.view.JstlView">
        <property name="url" value="/WEB-INF/view/xmlSample.jsp" />
    </bean>
</beans>

8. How to configure multiple view resolvers?

If multiple view resolver strategies are applied, you have to declare the priority through “order” property, where the lower order value has a higher priority, for example :

       <bean class="org.springframework.web.servlet.view.XmlViewResolver">
      <property name="location">
         <value>/WEB-INF/spring-views.xml</value>
      </property>
      <property name="order" value="0" />
 </bean>

 <bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
      <property name="basename" value="spring-views" />
      <property name="order" value="1" />
 </bean>

 <bean id="viewResolver"
       class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
              <property name="prefix">
                 <value>/WEB-INF/pages/</value>
              </property>
              <property name="suffix">
                 <value>.jsp</value>
              </property>
       <property name="order" value="2" />
        </bean>

9. Why to keep InternalResourceViewResolver at the end ?

InternalResourceViewResolver is subclass of UrlBasedViewResolver. This is used to resolve Servlet/Jsp view technologies at the end. Usually the controller will send the logical view name to the resolver. If its any resolver but InternalResourceViewResolver, then it has to map the logical view name using specific classes. If it cannot form a physical view name, then the controller will be redirected to next view resolver in order. But in case of InternalResourceViewResolver, it will form the physical Jsp page name and redirects the controller to the page. Until it lands on the Jsp page, it cannot verify the existence of the jsp page. That is why the internal resource view resolvers are ordered to execute at last so that if any view resolver cannot find a view, internal resource view resolver can be executed to find it. If internal resource view resolver also fails at last, that is a valid exception that should be caught and thrown.

10. What is the difference between @Component, @Controller, @Repository & @Service?What are Spring Stereotypes?

Spring @Component, @Repository, @Service and @Controller are Stereotype Annotations. @Component is generic stereotype annotation for any Spring-managed component.
Screenshot2B2019 06 232Bat2B11.48.58
@Controller
You cannot switch this annotation with any other like @Service or @Repository, even though they look same. The dispatcher scans the classes annotated with @Controller and detects @RequestMapping annotations within them. You can only use @RequestMapping on @Controller annotated classes.
@Service
This another specialized version of @Component to inform the spring component-scanning mechanism to load the service classes. These are introduced to in the spring framework to add any specific features to the service classes in the future.
@Repository
@Repository is specialized implementation of @Component for indicating the Data Access Objects (DAO). Advantage of using the @Repository annotation, importing the DAOs into the DI container and also this annotation makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException.
spring creates an instance of it in the IoC container as with any other stereotype annotation (@Component, @Service) but it can also add exception translation if you explicitly add this bean declaration to your config:
<bean class=”org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor”/>
This enables translation of native runtime resource exceptions that would otherwise be vendor-specific (database (oracle, etc), orm (hibernate, jpa, etc) to Spring’s runtime exception hierarchy regardless of what vendors you use over time.

11. Explain Model, ModelMap and ModelAndView?

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.