浅谈Listener、Filter、Servlet初始化顺序
likeo
10年前
Listener、Filter、Servlet都有一个初始化的过程,对应的方法分别为:
contextInitialized(ServletContextEvent arg0); // Listener init(FilterConfig filterConfig); // Filter init(ServletConfig config); // Servlet
那么它们的初始化顺序是什么呢?
Listener > Filter > Servlet
TestServlet.java:
package com.king; import java.io.IOException; import javax.servlet.GenericServlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class TestServlet extends GenericServlet { @Override public void init(ServletConfig config){ System.out.println("Servlet 初始化 。。。"); } @Override public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException { System.out.println("Servlet service 。。。"); } }
TestFilter.java:
package com.king; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class TestFilter implements Filter{ public void init(FilterConfig filterConfig) throws ServletException { System.out.println("Filter 初始化。。。"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("doFilter 。。。"); chain.doFilter(request, response); } public void destroy() { System.out.println("Filter 销毁。。。"); } }
TestListener.java:
package com.king; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class TestListener implements ServletContextListener{ public void contextInitialized(ServletContextEvent arg0) { System.out.println("Listener 初始化。。。"); } public void contextDestroyed(ServletContextEvent arg0) { System.out.println("Listener 销毁。。。"); } }
web.xml:
<xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>s<servlet-name> <servlet-class>com.cos.TestServlet<servlet-class> <servlet> <servlet-mapping> <servlet-name>s<servlet-name> <url-pattern>/login<url-pattern> <servlet-mapping> <filter> <filter-name>f<filter-name> <filter-class>com.cos.TestFilter<filter-class> <filter> <filter-mapping> <filter-name>f<filter-name> <url-pattern>/*<url-pattern> <filter-mapping> <listener> <listener-class>com.cos.TestListener<listener-class> <listener> <web-app>
启动tomcat后,在控制台里以此打印出:
Listener 初始化。。。
Filter 初始化。。。
信息: Server startup in 675 ms
可以看出Listener的初始化最早,Filter次之。他俩的初始化都是在容器启动完成之前初始化的。Servlet没有初始化,原因是没有匹配的请求进来。初始化的顺序跟Listener、Filter、Servlet在web.xml中的顺序无关。
而多个Filter或多个Servlet的时候,谁的mapping在前面,谁先初始化。