在Spring MVC程序中,配置Web.xml文件,要配置兩個Servlet。web
第一個是org.springframework.web.context.ContextLoaderServlet
,用於在Web程序啓動的時候,就加載一個配置文件,該配置文件的內容是爲全部其web組件所共享的。無需接受請求即加載該文件,web程序啓動的時候即加載了這個文件。示例以下:spring
<!-- The definition of the Root Spring Container shared by all Servlets and Filters --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param> <!-- Creates the Spring Container shared by all Servlets and Filters --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
第二個是org.springframework.web.servlet.DispatcherServlet
,該Servlet的做用在於,處理各類web請求,只有當接受到請求,纔會將這個DispatcherServlet所產生的上下文保存在Request中。示例以下:app
<!-- Processes application requests --> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>