模拟javaWeb责任链的设计

时间:2024-01-25 15:55:33

这篇文章介绍了责任链模式的应用:本文介绍如果自己实现一个责任链

定义请求和响应信息

简单定义请求类Request(封装一个字符串)

public class Request {
    String requestStr;

    public String getRequestStr() {
        return requestStr;
    }

    public void setRequestStr(String requestStr) {
        this.requestStr = requestStr;
    }
}

简单定义响应类Response

public class Response {
    String responseStr;

    public String getResponseStr() {
        return responseStr;
    }

    public void setResponseStr(String responseStr) {
        this.responseStr = responseStr;
    }
    
}

定义Filter(参数接收Request和Response)

至于为什么接收FilterChain(是为了下面filter里面能够调用FilterChain的doFilter()方法)

定义Filter接口

把Request对象和Response对象交给处理器Filter:处理器既能处理Request对象 也能处理Response对象

public interface Filter {
    void doFilter(Request request, Response response, FilterChain chain);
}

 定义两个Filter实现类

public class HTMLFilter implements Filter {

    @Override
    public void doFilter(Request request, Response response, FilterChain chain) {
        //process the html tag <>
        request.requestStr = request.requestStr.replace('<', '[')
                   .replace('>', ']') + "---HTMLFilter()";
        chain.doFilter(request, response, chain);
        response.responseStr += "---HTMLFilter()";
    }

}
View Code
public class SesitiveFilter implements Filter {

    @Override
    public void doFilter(Request request, Response response, FilterChain chain) {
        request.requestStr = request.requestStr.replace("被就业", "就业")
         .replace("敏感", "") + "---SesitiveFilter()";
        chain.doFilter(request, response, chain);
        response.responseStr += "---SesitiveFilter()";
    
    }

}
View Code

定义FilterChain

public class FilterChain implements Filter {
    List<Filter> filters = new ArrayList<Filter>();
    int index = 0;
    
    public FilterChain addFilter(Filter f) {
        this.filters.add(f);
        return this;
    }
    
    @Override
    public void doFilter(Request request, Response response, FilterChain chain) {
        if(index == filters.size()) return ;
        
        Filter f = filters.get(index);
        index ++;
        f.doFilter(request, response, chain);
    }
}

main()方法测试

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String msg = "大家好:),<script>,敏感,被就业,网络授课没感觉,因为看不见大家伙儿";
        Request request = new Request();
        request.setRequestStr(msg);
        Response response = new Response();
        response.setResponseStr("response");
        FilterChain fc = new FilterChain();
        fc.addFilter(new HTMLFilter())
          .addFilter(new SesitiveFilter())
          ;
        
        fc.doFilter(request, response, fc);
        System.out.println(request.getRequestStr());
        System.out.println(response.getResponseStr());
    }

}

以上代码特点是 Request的处理是正序 Response的处理时倒序:

方便大家看清步骤:这是断点执行顺序

Filter里面调用了filterChain的doFilter方法

FilterChain里面调用了filter的doFilter方法