Tomcat过滤器模拟

直接上代码Filter.java

public interface Filter {

    //过滤器

    public void doFilter(Request request,Response response,FilterChain chain);



}

FilterChain.java

public class FilterChain {

    //存放所有的过滤器

    private List<Filter> filters ;

    //记录当前过滤索引

    private int index;

    //过滤链初始化

    public FilterChain()

    {

        filters = new ArrayList<Filter>(10);

    }

    

    public void addFilter(Filter filter)

    {

        filters.add(filter);

    }

    /**

     * 迭代过滤

     */

    public void doFilter(Request request,Response response)

    {

        if ( index >= filters.size() )

            return;

        filters.get( index++ ).doFilter(request, response, this);

    }



}

Request.java

public class Request {

    

    private String value;



    public String getValue() {

        return value;

    }



    public void setValue(String value) {

        this.value = value;

    }

    

    @Override

    public String toString() {

        return this.value;

    }



}

Response.java

public class Response {

    

    private String value;



    public String getValue() {

        return value;

    }



    public void setValue(String value) {

        this.value = value;

    }

    

    @Override

    public String toString() {

        return this.value;

    }



}

FilterOne.java

public class FilterOne implements Filter{



    /**

     * 过滤FUCK字符

     */

    @Override

    public void doFilter(Request request, Response response, FilterChain chain) {

        System.out.println("进入过滤器FilterOne---------------------------------------");

        //执行下一个过滤器

        chain.doFilter(request, response);

        

        System.out.println("出去过滤器FilterOne---------------------------------------");

    }



}

FilterTwo.java

public class FilterTwo implements Filter{



    @Override

    public void doFilter(Request request, Response response, FilterChain chain) {

        System.out.println("进入过滤器FilterTwo---------------------------------------");

        //执行下一个过滤器

        chain.doFilter(request, response);

        

        System.out.println("出去过滤器FilterTwo---------------------------------------");

    }

    

}

Test.java

public class Test {

    

    public static void main(String[] args) {

        FilterChain chain = new FilterChain();

        chain.addFilter(new FilterOne());

        chain.addFilter(new FilterTwo());

        chain.doFilter(new Request(), new Response() );

    }



}

运行结果

进入过滤器FilterOne---------------------------------------

进入过滤器FilterTwo---------------------------------------

出去过滤器FilterTwo---------------------------------------

出去过滤器FilterOne---------------------------------------

 

你可能感兴趣的:(tomcat)