在一个大型项目中往往有多个servlet过滤器,但是这些servlet过滤器的执行顺序是怎样的呢?
请看一下例子:
创建两个简单的servlet文件
package filter;
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 Filter1 implements Filter {
public void destroy() {
}
public void init(FilterConfig config) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
System.out.println("filter1");
chain.doFilter(request, response);
System.out.println("filter1 go back");
} catch (Exception e) {
e.printStackTrace();
}
}
}
package filter;
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 Filter2 implements Filter {
public void destroy() {
}
public void init(FilterConfig config) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
System.out.println("filter2");
chain.doFilter(request, response);
System.out.println("filter2 go back");
} catch (Exception e) {
e.printStackTrace();
}
}
}
在web.xml里面添加映射文件:
<filter>
<filter-name>filter1</filter-name>
<filter-class>filter.Filter1</filter-class>
</filter>
<filter>
<filter-name>filter2</filter-name>
<filter-class>filter.Filter2</filter-class>
</filter>
<filter>
<filter-name>filter3</filter-name>
<filter-class>filter.Filter3</filter-class>
</filter>
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>filter2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
对于这个项目的任意一个jsp以及其他请求都要经过这两个servlet过滤器的过滤
因为<url-pattern>/*</url-pattern>
程序执行结果
filter1
filter2
filter2 go back
filter1 go back
如果把web.xml映射文件修改为
</filter>
<filter>
<filter-name>filter2</filter-name>
<filter-class>filter.Filter2</filter-class>
</filter>
<filter>
<filter-name>filter3</filter-name>
<filter-class>filter.Filter3</filter-class>
</filter>
<filter-mapping>
<filter-name>filter2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
则程序的执行结果为:
filter2
filter1
filter1 go back
filter2 go back
仔细观察这两个映射文件的不同之处我们可以看出,servlet过滤器的执行顺序就是servlet过滤器在web.xml里面映射文件的顺序,即定义越靠前的执行越早。
对于上例,如果再建立一个testfilter.jsp:
<head>
<title>Test Page</title>
</head>
<body>
Test filter1.
<% System.out.println("In testfilter.jsp now!"); %>
</body>
访问这个jsp文件后,在应用服务器控制台将输出:
filter2
filter1
In testfilter1.jsp now!
filter1 go back
filter2 go back