一、DispatcherServlet
1、在web.xml注册Servlet
<!--配置前端控制器:加载SpringMVC配置文件 【默认在WEB-INF下文件为 <servlet-name>-servlet.xml 】-->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--自定义设置SpringMVC的配置文件位置-->
<!--<init-param>-->
<!--<param-name>contextConfigLocation</param-name>-->
<!-- 此处指向的的是SpringMVC的配置文件 -->
<!--<param-value>classpath:xxx.xml</param-value>-->
<!--</init-param>-->
<!--设置servlet的加载时间
默认在第一次访问时加载
设置此标签会将servlet的加载时间提前到项目启动时
-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
2、工作流程:
3、类的继承关系:
4、DispatcherServlet请求处理流程:
二、Listener
1、在web.xml注册Listener
<!--自定义监听器-->
<listener>
<listener-class>com.jason.lee.mvc.listener.SpringListener</listener-class>
</listener>
2、实现Listener接口
public class SpringListener implements ServletContextListener {
// Public constructor is required by servlet spec
public SpringListener() {
System.out.println("SpringListener");
}
// -------------------------------------------------------
// ServletContextListener implementation
// -------------------------------------------------------
public void contextInitialized(ServletContextEvent sce) {
/* This method is called when the servlet context is
initialized(when the Web application is deployed).
You can initialize servlet context related data here.
*/
ApplicationContext ac = new ClassPathXmlApplicationContext("springTest.xml");
sce.getServletContext().setAttribute("ac", ac);
}
public void contextDestroyed(ServletContextEvent sce) {
/* This method is invoked when the Servlet Context
(the Web application) is undeployed or
Application Server shuts down.
*/
}
}
三、Filter
1、在web.xml注册Filter
<!--字符编码过滤器-->
<filter>
<filter-name>characterEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.jason.lee.filter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<!--精确配置:URL/Servlet-->
<url-pattern>/HelloServlet</url-pattern>
<servlet-name>HelloServlet</servlet-name>
</filter-mapping>
2、实现Filter接口
public class MyFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
System.out.println("MyFilter");
chain.doFilter(req, resp);
System.out.println("MyFilter");
}
public void init(FilterConfig config) throws ServletException {
}
}