1. What is the DispatcherServlet and what is it used for?
  • The DispatcherServlet is an implementation of Front Controller design pattern which handles all incoming web request to a Spring MVC application.

    A Front Controller pattern is a common pattern in web applications whose job is to receive all request and route it to different components of the application for actual processing.

  • In Spring MVC, DispatcherServlet is used for finding the correct Controller to process a request, which it does with the help of handler mapping e.g. @RequestMapping annotation.
  • It is also responsible for delegating logical view name to ViewResolver and then sending the rendered response to the client.
  • Spring’s web MVC framework is, like many other web MVC frameworks, request-driven, designed around a central servlet that dispatches requests to controllers and offers other functionality that facilitates the development of web applications. Spring’s DispatcherServlet however, does more than just that.
  • The request processing workflow of the Spring Web MVC DispatcherServlet is illustrated in the following diagram.

  • The DispatcherServlet is an actual Servlet (it inherits from the HttpServlet base class),
    and as such is declared in the web.xml of your web application.
    You need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the same web.xml file.
    This is standard J2EE servlet configuration;
    the following example shows such a DispatcherServlet declaration and mapping:
<web-app>

    <servlet>
        <servlet-name>example</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>*.form</url-pattern>
    </servlet-mapping>

</web-app>

In the preceding example, all requests ending with .form will be handled by the example DispatcherServlet.
This is only the first step in setting up Spring Web MVC.

Reference: https://docs.spring.io/spring/docs/3.0.0.M4/spring-framework-reference/html/ch15s02.html

spring_dispatcherservlet

 

Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet −

  • After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller.
  • The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and 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.

All the above-mentioned components, i.e. HandlerMapping, Controller, and ViewResolver are parts of WebApplicationContext w which is an extension of the plainApplicationContext with some extra features necessary for web applications.

2. How is DispatcherServlet instantiated ?
Is the DispatcherServlet instantiated via an application context?

No, it is not instantiated via an application context.

  • DispatcherServlet is instantiated by Servlet containers like Tomcat or Jetty.
  • You must define DispatcherServlet into the web.xml file.
  • If “load-on-startup” tag is 1 it means DispatcherServlet is instantiated when you deploy Spring MVC application to Tomcat or any other Servlet container.

Upon initialization of a DispatcherServlet, the framework looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and create the beans defined there, overriding the definitions of any beans defined with the same name in the global scope.

Consider the following DispatcherServlet servlet configuration (in the web.xml file):

<web-app>

    <servlet>
        <servlet-name>golfing</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>codinko</servlet-name>
        <url-pattern>/codinko/*</url-pattern>
    </servlet-mapping>

</web-app>

With the above servlet configuration in place, you will need to have a file called /WEB-INF/codinko-servlet.xml in your application; this file will contain all of your Spring Web MVC-specific components (beans).

You can change the exact location of this configuration file through a servlet initialization parameter.

Reference: https://docs.spring.io/spring/docs/3.0.0.M4/spring-framework-reference/html/ch15s02.html

3. What is WebApplicationContext? and its relation with the Dispatcher Servlet?

  • The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications.
  • It differs from a normal ApplicationContext in that
    – it is capable of resolving themes (see Using themes), and that
    – it knows which servlet it is associated with (by having a link to the ServletContext).
  • The WebApplicationContext is bound in the ServletContext, and by using static methods on the RequestContextUtils class you can always look up the WebApplicationContext if you need access to it.
  • The Spring DispatcherServlet uses special beans to process requests and render the appropriate views. These beans are part of Spring Framework. You can configure them in the WebApplicationContext, just as you configure any other bean. However, for most beans, sensible defaults are provided so you initially do not need to configure them. These beans are described in the following table.

Special beans in the WebApplicationContext

Bean type Explanation
controllers Form the C part of the MVC.
handler mappings Handle the execution of a list of pre-processors and post-processors and controllers that will be executed if they match certain criteria (for example, a matching URL specified with the controller).
view resolvers Resolves view names to views.
locale resolver locale resolver is a component capable of resolving the locale a client is using, in order to be able to offer internationalized views
Theme resolver theme resolver is capable of resolving themes your web application can use, for example, to offer personalized layouts
multipart file resolver Contains functionality to process file uploads from HTML forms.
handler exception resolvers Contains functionality to map exceptions to views or implement other more complex exception handling code.

Read more here : https://docs.spring.io/spring/docs/3.0.0.M4/spring-framework-reference/html/ch15s02.html

4. What is the @Controller annotation used for? How can you create a controller without an annotation?

  • The @Controller is a Spring MVC annotation to define Controller but in reality, it’s just a stereotype annotation.
  • You can even create a controller without @Controller by annotating the Spring MVC Controller classes using @Component annotation.

The request mapping to the handler method is done using @RequestMapping annotation.

 

5. What is the ContextLoaderListener and what does it do? 

  • The ContextLoaderListener is a listener which helps to bootstrap Spring MVC.
    Bootstrap listener to start up and shut down Spring’s root WebApplicationContext
  • It loads and create ApplicationContext, so you don’t have to write explicit code to do create it. ( The application context is where Spring beans are defined. For a Web application, there is is a subclass called WebApplicationContext).
  • The ContextLoaderListener also tie the lifecycle of the ApplicationContext to the lifecycle of the ServletContext.
    You can get the ServletContext from WebApplicationContext using getServletContext() method.
  • Simply delegates to ContextLoader as well as to ContextCleanupListener
  • As of Spring 3.1, ContextLoaderListener supports injecting the root web application context via the ContextLoaderListener(WebApplicationContext) constructor.
public class ContextLoaderListener
extends ContextLoader
implements ServletContextListener

6. Where is ContextLoaderListener configured?

  • The ContextLoaderListener is configured in web.xml as listener<listener>
    <listener-class>
    org.springframework.web.context.ContextLoaderListener
    </listener-class>
    </listener>When the Spring MVC web application is deployed,
    Servlet container creates an instance of ContextLoaderListener class which loads the Spring’s WebApplicationContext. 
  • Remember that DispatcherServlet is also instantiated by Servlet container, which triggers another workflow of handling requests.

7. How is an incoming request mapped to a controller and mapped to a method?
or
How does DispatcherServlet knows which Controller should process the request?

  •  Using Handler mappings
  • Remember we mentioned about Request Mappings.
  • Spring uses handler mappings to associate controllers with requests, two of the commonly used handler mappings are BeanNameUrlHandlerMapping and SimpleUrlHandlerMapping.
  • In BeanNameUrlHandlerMapping, when the request url matches the name of the bean, the class in the bean definition is the controller that will handle the request.
  • On the other hand, In SimpleUrlHandlerMapping, the mapping is more explicit. You can specify the number of URLs and each URL can be explicitly associated with a controller.

f you are using annotations to configure Spring MVC,  then @RequestMapping annotations is used to map an incoming request to a controller and a handler method.

You can also configure @RequestMapping annotation by URI Path, by query parameters, by HTTP methods of a request and by HTTP headers present in the request.

8. What is the @RequestParam used for?

The @RequestParam is a Spring MVC annotation which is used to extract request parameter or query parameters from URL in Controller’s handler method as shown below:public String getEmployeeName()(@RequestParam(“id”) long id){
….
return “name”;
}- The @RequestParam annotation also supports data type conversion e.g. you can see here a String is converted to long automatically but it can also result in an exception if the query parameter is not present or in case of a type mismatch. You can also make the parameter optional by using required=false e.g. @RequestParam(value=”id”, required=false )

9. What are the differences between @RequestParam and @PathVariable? 
  • Even though both @RequestParam and @PathVariable annotations are used to extract some data from the URL, there is a key difference between them.
  • @RequestParam is used to for accessing the values of the query parameters
    e.g. anything after “?” in URL
  • @PathVariable is used for accessing the values from the URI template.For example, if the given URL is http://localhost:8080/codinko/posts/1234/?format=json then,Using @RequestParam annotation, you can access the value of the query parameter “format” ie: json.Using @PathVariable annotation, you can get /posts/{id} which will give you 1234.

    Here is another example of @PathVariable,

    @RequestMapping(“/posts/{id}” )
    public String personDetail (@PathVariable (“id” ) long id) {…}

10. What are some of the valid return types of a controller method? 

  • Controller methods are usually annotated by @RequestMapping to map a request.
  • There are many return types are available for a controller method in Spring MVCSome of the popular ones are:
  1. String
  2. void
  3. View
  4. ModelAndView (Class)
  5. Model (Interface)
  6. Map
  7. HttpEntity<?> or ResponseEntity<?>
  8. HttpHeaders
  • Every return type has its specific use.
    For example, if you are using String then it means Controller just return View Name and this view name will be resolved by ViewResolver.
  • If you don’t want to return any view name mention return type void.
  • If you want to set view name as well as want to send some object , then use ModelAndView as a return type.

11. What is a View and why does Spring offers different types of View?

Read: https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/view.html

  • A View is an interface in Spring MVC application whose implementations are responsible for rendering context and exposing the model.
  • A single view exposes multiple model attributes.
  • Views in Spring MVC can be beans also.
  • They are likely to be instantiated as beans by a ViewResolver.
  • As this interface is stateless, view implementations should be thread-safe
  • By using ViewResolver, a logical name of view can be resolved into different types of View implementation e.g. JstlView for displaying JSP or other view implementations for FreeMarker and Velocity.

12. How is the right View chosen when it comes to the rendering phase?

The right View is chosen by ViewResolver in Spring MVC.

When Controller returns a logical view name to DispatcherServlet, it consults ViewResolver to find the right View.

The ViewResolver depending upon its implementation resolves the logical view into a physical resource e.g. a JSP page or a FreeMarker template.

For example, InternalResourceViewResolver is a default view resolvers which converts logical view name e.g. “books” to “/WEB-INF/books.jsp” using prefix and suffix.

Spring’s view resolution is extremely flexible.
  • Controller is typically responsible for preparing a model Map with data and selecting a view name but it can also write directly to the response stream and complete the request.
  • View name resolution is highly configurable through file extension or Accept header content type negotiation, through bean names, a properties file, or even a custom ViewResolver implementation.
  • The model (the M in MVC) is a Map interface, which allows for the complete abstraction of the view technology.
  • You can integrate directly with template based rendering technologies such as JSP, Velocity and Freemarker, or directly generate XML, JSON, Atom, and many other types of content.
  • The model Map is simply transformed into an appropriate format, such as JSP request attributes, a Velocity template model.
13. What is Model?
  • The model (the M in MVC) is a Map interface, which allows for the complete abstraction of the view technology
  • Basically it is used to encapsulate the data to be used for rendering.
  • Model is always created and passed to the view in Spring MVC.

– If a mapped controller method has Model as a method parameter, then a model instance is automatically injected by Spring framework to that method.

Any attributes set on the injected model are preserved and passed to the View. Here is an example of using Model in Spring MVC:

public String employeeDetails(Model model) {

model.addAttribute(“name”, “Harley”);

}

14. Why do you need access to the model in your View? Where does it set initially?

It’s the model which contains the data to be rendered.
  • You need to have access to the model in your View to render the output.
  • The Model comes with the Controller, which process their client request and encapsulate the output into a Model object.

15. What is the purpose of the session scope? 

  • To create an instance of the bean for an HTTP Session.
  • This means the same bean can serve multiple requests if it is scoped in session. You can define the scope of a Spring bean using scope attribute or @Scope annotation in Spring MVC application.

16.  What is the default scope in the web context? 

  • The singleton scope is the default scope for a Spring bean even in the web context.
  • The other three Web context-aware scopes are a request, session, and global-session, which are only available in a web application aware ApplicationContext object.
17. Explain InternalResourceViewResolver

In Spring MVC, A ViewResolver returns View to handle to output rendering based on the Logical View Name (provided by the controller) and locale. This way controller is not coupled to specific view technology e.g. JSP or FreeMarker it only returns the logical view name.

InternalResourceViewResolver is the default View resolver configured in Spring MVC and DispatcherServlet uses it to find the correct view. InternalResourceViewResolver is used to render JSPs (JstlView).

It Configures prefix and suffix to logical view name which then results in a path to specific JSP as shown below:

<bean class= “org.springframework.web.servlet.view.InternalResourceViewResolver” >
<property name= “prefix” value= “/WEB-INF/” />
<property name =”suffix” value =”.jsp” />
</bean>So if Controller returns “books” as logical view name, the InternalViewResolver will return /WEB-INF/books.jsp and DispatcherServlet will forward the request to this JSP page for rendering.
———

Good links:

  • https://docs.spring.io/spring/docs/current/spring-framework-reference/index.html
  • https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html