JavaWeb Filter 的执行顺序

JavaWeb Filter 的执行顺序

AFilter 类:
package com.ztesoft.sequence;

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;

/**
 * Servlet Filter implementation class AFilter
 */
@WebFilter("/sequence/test.jsp")
public class AFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		System.out.println("1");
		chain.doFilter(request, response);
		System.out.println("2");
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}

BFilter 类:
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;

/**
 * Servlet Filter implementation class BFilter
 */
@WebFilter("/sequence/test.jsp")
public class BFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		System.out.println("3");
		chain.doFilter(request, response);
		System.out.println("4");
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}

初始界面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>




Insert title here



	To Test Page



拦截页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>




Insert title here



	

This is Test Page

<% System.out.println("5"); %>

运行之后得到的结果为: 1 、 3 、 5 、 4 、 2
原因:
         首先,Filter的加载顺序,是由web.xml中配置的的顺序有关,越往前的越先执行,进行目标的拦截。若用FIlter类,改写url-pattern,则加载的顺序与Filter的名字有关,类似于字符串比较大小,越小的越先执行。
         本例子中,首先执行AFilter,所以先输出 1 ,而后调用chain.doFilter方法,到下一个Filter,而该方法后面的内容类似于断点,需要进行回执行。所以就执行了 3 ,5 。结束后,开始进行回执行,首先回到较近的Filter ,执行 4 ,最后执行 2 。

你可能感兴趣的:(JavaWeb)