|
Servlet@WebFilter注解方式——过滤器链的执行顺序
执行顺序和类名字符排序有关!
以下是测试代码:
Filter0 .javapackage 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;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* 过滤器链
* @author xanwidtf@foxmail.com
*
*/
@WebFilter(filterName="FirstFilter",urlPatterns="/index.jsp")
public class Filter0 implements Filter {
@Override
public void destroy() {
System.out.println("FirstFilter过滤器destroy方法执行~");
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
System.out.println("Start……doFilter……FirstFilter");
arg2.doFilter(arg0, arg1);
// HttpServletRequest request = (HttpServletRequest) arg0;
// HttpServletResponse response = (HttpServletResponse) arg1;
// response.sendRedirect(request.getContextPath()+"/First.jsp");
System.out.println("End……doFilter……FirstFilter");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
System.out.println("过滤器init()执行了~");
}
} |
Filter1.java
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;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebFilter(filterName="SecondFilter",urlPatterns="/index.jsp")
public class Filter1 implements Filter {
@Override
public void destroy() {
System.out.println("SecondFilter过滤器destroy方法执行~");
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
System.out.println("Start……doFilter……SecondFilter");
arg2.doFilter(arg0, arg1);
// HttpServletRequest request = (HttpServletRequest) arg0;
// HttpServletResponse response = (HttpServletResponse) arg1;
// response.sendRedirect(request.getContextPath()+"/Second.jsp");
System.out.println("End……doFilter……SecondFilter");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
System.out.println("SecondFilter过滤器destroy方法执行~");
}
} |
输出:
Start……doFilter……FirstFilter
Start……doFilter……SecondFilter
处理过程执行了~
End……doFilter……SecondFilter
End……doFilter……FirstFilter
如果把Filter0改名为Filter2将会输出:
Start……doFilter……SecondFilter
Start……doFilter……FirstFilter
处理过程执行了~
End……doFilter……FirstFilter
End……doFilter……SecondFilter
程序猿的技术大观园:www.javathinker.net
|
|