Tomcat過濾器模擬

直接上代碼Filter.javajava

public interface Filter {
    //過濾器
    public void doFilter(Request request,Response response,FilterChain chain);

}

FilterChain.javaide

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.javathis

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.javaspa

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.javacode

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.javablog

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() );
    }

}

運行結果get

進入過濾器FilterOne---------------------------------------
進入過濾器FilterTwo---------------------------------------
出去過濾器FilterTwo---------------------------------------
出去過濾器FilterOne---------------------------------------
相關文章
相關標籤/搜索