ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • DispatcherServlet in Spring
    Framework/SPRING 2019. 9. 28. 23:46

    1. Overview

    In the Front Controller design pattern, a single controller is responsible for directing incoming HTTP requests to all of an application's other controllers and handlers. Spring's DispatcherServlet implements this pattern and is responsible for correctly coordinating the HTTP requests to their right handlers. It is inherited from javax.servlet.http.HttpServlet, it is typically configured in the web.xml file. 

     

    A web application can define any number of DispatcherServlet instances. Each servlet will operate in its own namespace, loading its own application context with mappings, handlers, etc. Only the root application context as loaded by ContextLoaderListener will be shared. In most cases, applications have only single DispatcherServlet with the context-root URL "/", all requests coming to that domain will be handled by it.

     

    DispatcherServlet uses Spring configuration classes to discover the delegate components it needs for request mapping, view resolution, exception handling, and etc.

     

     

     

    2. Description

    2.1 Workflow of DispatcherServlet

    When a web request is sent to a Spring MVC application, 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.

     

    2.2 How DispatcherServlet uses WebApplicationContext 

    In a Spring-based application, our application objects live within an object container. This container creates objects and associations between objects and manages their complete life cycle. These container objects are called Spring-managed beans(or simple beans), and the container is called an application context(via class ApplicationContext) in the Spring world.

     

    Web applicationConext is an extension of a plain ApplicationContext. it is web-aware ApplicationContext which means has Servlet Context information. When DispatcherServlet is loaded, it looks for the bean configuration file of WebApplicationContext and initializes it.

     

    By having access to Servlet context, any spring bean which implements ServletContextAware interface can get access to ServletContext instance and do many things with it. For example, it can get context to init parameters, get context root information and get resources location inside web application folders.

     

    2.3 DispatcherServlet Request Processing 

    • The WebApplicationContext associated to a DispatcherServlet under the key DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE is searched for and made available to all of the elements of the process
    • The DispatcherServlet finds all implementations of the HandlerAdapter interface configured for your dispatcher using getHandler() – each found and configured implementation handles the request via handle() through the remainder of the process
    • the LocaleResolver is optionally bound to the request to enable elements in the process to resolve the locale
    • The ThemeResolver is optionally bound to the request to let elements, such as views, determine which theme to use
    • If a MultipartResolver is specified, the request is inspected for MultipartFiles – any found are wrapped in a MultipartHttpServletRequest for further processing
    • HandlerExceptionResolver implementations declared in the WebApplicationContext pickup exceptions that are thrown during processing of the request

    2.4 HTTP Request Handling

    The core responsibility of a DispatcherServlet is to dispatch incoming HttpRequests to the correct handlers specified with the @Controller or @RestController annotations. 

     

    2.5 The ViewResolver Interface

    A viewResolver is attached to a DispatcherServlet as a configuration setting on an ApplicationContext object. A ViewResolver determines both what kind of views are served by the dispatcher and from where they are served

     

    @Configuration
    @EnableWebMvc
    @ComponentScan("com.baeldung.springdispatcherservlet")
    public class AppConfig implements WebMvcConfigurer {
     
        @Bean
        public UrlBasedViewResolver viewResolver() {
            UrlBasedViewResolver resolver
              = new UrlBasedViewResolver();
            // Setting the prefix, which sets the default URL path to find the set views within
            resolver.setPrefix("/WEB-INF/jsp/");
            // The default view type which is set via the suffix
            resolver.setSuffix(".jsp");
            // Setting a view class on the resolver which allows technologies like 
            // JSTL or Tiles to be associated with the rendered views
            resolver.setViewClass(JstlView.class);
            return resolver;
        }
    }

    Here's an example path configuration for an InternalViewResolver using Spring's XML configuration. This is how precisely a dispatcher's ViewResolver and the overall project directory structure are related

     

    <property name="prefix" value="/jsp/"/>
    
    // Assume that our application is being hosted on:
    
    http://localhost:8080/
    
    // Assuming that our application is called dispatcherexample-1.0.0, our JSP views will be accessible from:
    
    http://localhost:8080/dispatcherexample-1.0.0/jsp/
    
    // The path for these views within an ordinary Spring project with Maven is this:
    
    
    src -|
         main -|
                java
                resources
                webapp -|
                        jsp
                        WEB-INF
                        
    // The default location for views is within WEB-INF. 
    // The path specified for our InternalViewResolver in the snippet 
    // above determines the subdirectory of ‘src/main/webapp' in which 
    // your views will be available.

     

     

    3. Example

    3.1 DispatcherServlet XML based configuration

    <!-- web.xml -->
    <web-app>
     
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
     
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet-context.xml</param-value>
      </context-param>
     
      <servlet>
        <servlet-name>dispatcher-servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>
     
      <servlet-mapping>
        <servlet-name>dispatcher-servlet</servlet-name>
        <url-pattern>/*</url-pattern>
      </servlet-mapping>
     
    </web-app>

    In the above code, dispatcher-servlet-context.xml file will contain all beans definitions and associations which will be available to DispatcherServlet. These bean definitions will override the definitions of any beans defined with the same name in the global scope. e.g.

    <!-- applicationContext.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-2.5.xsd">
     
        <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
            <property name="prefix">
                <value>/WEB-INF/views/</value>
            </property>
            <property name="suffix">
                <value>.jsp</value>
            </property>
        </bean>
     
    </beans>

    3.2 DispatchServlet Java-based configuration

    Starting from Servlet 3.0, in addition to declarative configuration in the web.xml file, DispatcherServlet can be configured programmatically by implementing or extending either of these three support classes provided by Spring –

     

    • WebAppInitializer interface
    • AbstractDispatcherServletInitializer abstract class
    • AbstractAnnotationConfigDispatcherServletInitializer abstract class

    4. References

    https://www.baeldung.com/register-servlet

    https://www.baeldung.com/spring-dispatcherservlet

    https://stackoverflow.com/questions/2769467/what-is-dispatcher-servlet-in-spring

    https://howtodoinjava.com/spring-mvc/spring-mvc-hello-world-example/

    https://howtodoinjava.com/spring5/webmvc/spring-dispatcherservlet-tutorial/

    'Framework > SPRING' 카테고리의 다른 글

    Spring MVC and Request Life Cycle  (0) 2020.02.03
    Spring Bean Scopes  (0) 2019.09.29
    Spring Security  (0) 2019.09.20
    Transaction Management  (0) 2019.09.17
    Spring Session  (0) 2019.08.27

    댓글

Designed by Tistory.