<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # Spring `DispatcherServlet` – 它是如何工作的? > 原文: [https://howtodoinjava.com/spring5/webmvc/spring-dispatcherservlet-tutorial/](https://howtodoinjava.com/spring5/webmvc/spring-dispatcherservlet-tutorial/) 了解 Spring 的[`DispatcherServlet`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html)類,其職責以及如何使用示例進行配置。 ## 1\. 什么是 Spring `DispatcherServlet` `DispatcherServlet`充當基于 Spring 的 Web 應用程序的[前控制器](https://en.wikipedia.org/wiki/Front_controller)。 它提供了一種用于請求處理的機制,其中實際工作由可配置的委托組件執行。 它繼承自[`javax.servlet.http.HttpServlet`](https://tomcat.apache.org/tomcat-7.0-doc/servletapi/javax/servlet/http/HttpServlet.html),通常在`web.xml`文件中進行配置。 Web 應用程序可以定義任意數量的`DispatcherServlet`實例。 每個 servlet 將在其自己的名稱空間中運行,并使用映射,處理器等加載其自己的應用程序上下文。只有[`ContextLoaderListener`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/context/ContextLoaderListener.html)加載的根應用程序上下文(如果有)將被共享。 在大多數情況下,應用程序僅具有上下文根 URL `(/)`的單個`DispatcherServlet`,即,到達該域的所有請求都將由該域處理。 `DispatcherServlet`使用 Spring 配置類發現請求映射,視圖解析,異常處理等所需的委托組件。 ## 2\. 如何使用`WebApplicationContext` 讓我們了解調度程序 servlet 在內部如何工作? 在基于 Spring 的應用程序中,我們的應用程序對象位于對象容器中。 該容器創建對象和對象之間的關聯,并管理它們的完整生命周期。 這些容器對象稱為 Spring 管理的 Bean(或簡稱為 Bean),在 Spring 世界中,該容器稱為**應用程序上下文**(通過類[`ApplicationContext`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/ApplicationContext.html))。 [`WebApplicationContext`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/context/WebApplicationContext.html)是普通`ApplicationContext`的擴展。 它是網絡感知的`ApplicationContext`,即它具有 Servlet 上下文信息。 加載`DispatcherServlet`后,它將查找`WebApplicationContext`的 bean 配置文件并對其進行初始化。 通過訪問 Servlet 上下文,任何實現[`ServletConextAware`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/context/ServletContextAware.html)接口的 spring bean – 都可以訪問[`ServletContext`](https://docs.oracle.com/javaee/7/api/javax/servlet/ServletContext.html)實例并用它做很多事情。 例如,它可以獲取上下文初始化參數,獲取上下文根信息以及獲取 Web 應用程序文件夾內的資源位置。 ## 3\. `DispatcherServlet` XML 配置 讓我們看看典型的`DispatcherServlet`聲明和初始化的樣子。 `web.xml` ```java <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> ``` 在上面的代碼中,`dispatcher-servlet-context.xml`文件將包含所有可用于`DispatcherServlet`的 bean 定義和關聯。 這些 bean 定義將覆蓋在全局范圍內用相同名稱定義的任何 bean 的定義。 例如 `applicationContext.xml` ```java <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> ``` ## 4\. `DispatcherServlet` Java 配置 從 Servlet 3.0 開始,除了`web.xml`文件中的聲明性配置外,還可以通過實現或擴展 Spring 提供的這三個支持類之一來以編程方式配置`DispatcherServlet`: * [`WebAppInitializer`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/WebApplicationInitializer.html)界面 * [`AbstractDispatcherServletInitializer`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/support/AbstractDispatcherServletInitializer.html)抽象類 * [`AbstractAnnotationConfigDispatcherServletInitializer`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/support/AbstractAnnotationConfigDispatcherServletInitializer.html)抽象類 #### 4.1. `WebAppInitializer`示例 在下面的類中,`WebApplicationInitializer`確保`SpringServletContainerInitializer`檢測到類`ApplicationInitializer`(它本身會自動運行),并用于初始化任何 Servlet 3 容器。 **spring boot `DispatcherServlet`映射**的示例。 `ApplicationInitializer.java` ```java public class ApplicationInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { XmlWebApplicationContext appContext = new XmlWebApplicationContext(); appContext.setConfigLocation("/WEB-INF/dispatcher-servlet-context.xml"); ServletRegistration.Dynamic registration = servletContext .addServlet("rootDispatcher", new DispatcherServlet(appContext)); registration.setLoadOnStartup(1); registration.addMapping("/"); } } ``` #### 4.2. 完整的基于 Java 的初始化 `ApplicationInitializer.java` ```java public class ApplicationInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext container) { // Create the 'root' Spring application context AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(AppConfig.class); // Manage the lifecycle of the root application context container.addListener(new ContextLoaderListener(rootContext)); // Create the dispatcher servlet's Spring application context AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext(); dispatcherContext.register(DispatcherConfig.class); ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } } ``` 在上面的代碼中,`AppConfig`和`DispatcherConfig`類定義將在 Web 應用程序上下文中的 spring 托管 bean。 #### 4.3. `AbstractDispatcherServletInitializer`示例 這是在 Servlet 上下文中注冊`DispatcherServlet`的`WebApplicationInitializer`實現的基類。 `ApplicationInitializer.java` ```java public class ApplicationInitializer extends AbstractDispatcherServletInitializer { @Override protected WebApplicationContext createRootApplicationContext() { return null; } @Override protected WebApplicationContext createServletApplicationContext() { XmlWebApplicationContext cxt = new XmlWebApplicationContext(); cxt.setConfigLocation("/WEB-INF/dispatcher-servlet-context.xml"); return cxt; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } //Register filters @Override protected Filter[] getServletFilters() { return new Filter[] { new HiddenHttpMethodFilter(), new CharacterEncodingFilter() }; } } ``` 請注意,如果您需要自定義`DispatcherServlet`,則可以覆蓋`createDispatcherServlet()`方法。 #### 4.4. `AbstractAnnotationConfigDispatcherServletInitializer`示例 該類擴展了`AbstractDispatcherServletInitializer`并隱式地執行了一些操作,否則您可能會自己做。 另一個優點是,您現在可以使用 Spring 提供的便利類,而不必手動配置`DispatcherServlet`和/或`ContextLoaderListener`。 對于使用基于 Java 的 Spring 配置的應用程序,這是首選方法。 它使您能夠啟動 servlet 應用程序上下文以及根應用程序上下文。 `AppInitializer.java` ```java public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] { RootConfig.class }; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[] { WebMvcConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } } ``` 這里`RootConfig`和`WebMvcConfig`類用于在 root 和 servlet 上下文范圍內配置 bean。 > 閱讀更多: [Spring 5 MVC 示例](https://howtodoinjava.com/spring5/webmvc/spring5-mvc-hibernate5-example/) ## 5\. 支持`DispatcherServlet`的 Bean 收到網絡請求后,`DispatcherServlet`將執行一組操作以進行請求處理。 為此,它使用了一組支持 bean。 下表列出了這些默認配置的 Bean 及其職責: | Bean | 職責范圍 | | --- | --- | | `HandlerMapping` | 將傳入的 Web 請求映射到處理器以及預處理器和后處理器 | | `HandlerAdapter` | 調用用于解析參數和依賴項的處理器,例如用于 URL 映射的控制器方法端點的帶注解的參數 | | `HandlerExceptionResolver` | 允許以編程方式處理異常并將異常映射到視圖 | | `ViewResolver` | 解析邏輯視圖名稱以查看實例 | | `LocaleResolver` | 解決客戶的語言環境以實現國際化 | | `LocaleContextResolver` | `LocaleResolver`的更擴展,帶有時區信息 | | `ThemeResolver` | 解決了在您的應用中配置的主題,以增強用戶體驗 | | `MultipartResolver` | 處理多部分文件上傳作為 HTTP 請求的一部分 | | `FlashMapManager` | 管理`FlashMap`實例,這些實例在彼此重定向的請求之間存儲臨時 Flash 屬性 | 如果要更改任何 bean 的任何特定行為,則需要覆蓋它。 ## 6\. Spring `DispatcherServlet`示例 為了演示`DispatcherServlet`的使用,我編寫了一個非常簡單的應用程序,該應用程序僅配置了調度程序 servlet 并覆蓋了視圖解析程序 bean。 #### 6.1. 項目結構 ![Spring5 MVC Project Structure](https://img.kancloud.cn/54/73/5473a8056d46bb8ecffdf0b4c5337cab_414x433.jpg) Spring5 MVC 項目結構 #### 6.2. `AppInitializer.java` `AppInitializer.java` ```java package com.howtodoinjava.demo.spring.config; public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] { }; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[] { WebMvcConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } } ``` #### 6.3. `WebMvcConfig.java` `WebMvcConfig.java` ```java @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.howtodoinjava.demo.spring"}) public class WebMvcConfig implements WebMvcConfigurer { @Bean public InternalResourceViewResolver resolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setViewClass(JstlView.class); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); return resolver; } } ``` #### 6.4. `HomeController.java` `HomeController.java` ```java @Controller public class HomeController { @GetMapping("/") public String homeInit(Locale locale, Model model) { return "home"; } } ``` #### `home.jsp` `home.jsp` ```java <html> <head> <title>Spring 5 Web MVC Example</title> </head> <body> <h1>HowToDoInJava.com</h1> <h2>Spring 5 Web MVC DispatcherServlet Example</h2> </body> </html> ``` #### 6.5. `pom.xml` `pom.xml` ```java <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd; <modelVersion>4.0.0</modelVersion> <groupId>com.howtodoinjava.spring5.mvc</groupId> <artifactId>spring5-webmvc-demo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>spring5-webmvc-demo Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <failOnMissingWebXml>false</failOnMissingWebXml> <spring.version>5.2.0.RELEASE</spring.version> <jstl.version>1.2.1</jstl.version> <tld.version>1.1.2</tld.version> <servlets.version>3.1.0</servlets.version> <jsp.version>2.3.1</jsp.version> </properties> <dependencies> <!-- Spring MVC Dependency --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- JSTL Dependency --> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>javax.servlet.jsp.jstl-api</artifactId> <version>${jstl.version}</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>${tld.version}</version> </dependency> <!-- Servlet Dependency --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlets.version}</version> <scope>provided</scope> </dependency> <!-- JSP Dependency --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>${jsp.version}</version> <scope>provided</scope> </dependency> </dependencies> <build> <sourceDirectory>src/main/java</sourceDirectory> <resources> <resource> <directory>src/main/resources</directory> </resource> </resources> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <path>/</path> </configuration> </plugin> </plugins> </build> </project> ``` #### 6.6. 運行應用程序 要運行應用程序,請執行 maven 目標:`tomcat7:run`。 現在在瀏覽器中打開`http://localhost:8080`。 ![Spring DispatcherServlet Demo Screen](https://img.kancloud.cn/b3/6a/b36a55fa68c9b0c457e186c0590ce88b_521x273.jpg) Spring `DispatcherServlet`示例截圖 將我的問題放在評論部分。 [下載源碼](https://github.com/lokeshgupta1981/spring-webmvc) 學習愉快!
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看