首页 > 代码库 > Spring MVC------->version4.3.6-------->知识点------>DispatchServlet

Spring MVC------->version4.3.6-------->知识点------>DispatchServlet

          DispatchServlet

1.概述:

    • The DispatcherServlet is an actual Servlet (it inherits from the HttpServlet base class)
    •  它用于拦截用户请求,并且将请求交给相应的handler处理(即交给@Controller   @RequestMapping类来处理)

2.配置DispatchServlet,使得它能够拦截相应的请求 (也即URL mapping)     

   概述:

      有多种方法可以使得DispatcherServlet能够拦截相应的URL请求(即拦截类似“/example/*”之类的请求)

      方法一,使用code-based configuration  

        • /**
           * @author chen
           * @description 此类用于初始化spring web mvc中的DispatchServlet
           *                 使得"/example/*"之类的url请求可以被dispatchServlet拦截
           * */
          public class InitializeSpringMVC implements WebApplicationInitializer{
              @Override
              public void onStartup(ServletContext container) {
                  ServletRegistration.Dynamic registration = container.addServlet("example", new DispatcherServlet());
                  registration.setLoadOnStartup(1);
                  registration.addMapping("/example/*");
              }
          
          }

          In the preceding example, all requests starting with /example will be handled by the DispatcherServlet instance named example.

        • WebApplicationInitializer is an interface provided by Spring MVC that ensures your code-based configuration is detected and automatically used to initialize any Servlet 3 container.

        • An abstract base class implementation of this interface named AbstractAnnotationConfigDispatcherServletInitializer makes it even easier to register the DispatcherServlet by simply specifying its servlet mapping and listing configuration classes - it’s even the recommended way to set up your Spring MVC application. See Code-based Servlet container initialization for more details.

 

    方法二,使用web.xml来配置URL 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>/example/*</url-pattern>
              </servlet-mapping>
          
          </web-app>

          In the preceding example, all requests starting with /example will be handled by the DispatcherServlet instance named example.

                

 

 

 

 

Spring MVC------->version4.3.6-------->知识点------>DispatchServlet