简介:javaweb中filter技术用的就是责任链模式。
例子:
- 假设请求和响应都是一个字符串。
public class Request { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
public class Response { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
- 定义一个处理器接口、具体的处理器实现类。
public interface Filter { void doFilter(Request request,Response response,FilterChain filterChain); }
一系列处理器实现类
public class FilterOne implements Filter { @Override public void doFilter(Request request, Response response, FilterChain filterChain) { System.out.println("FilterOne:"+request.getMessage()); filterChain.doFilter(request,response,filterChain); System.out.println("FilterOne:"+response.getMessage()); } }
public class FilterTwo implements Filter { @Override public void doFilter(Request request, Response response, FilterChain filterChain) { System.out.println("FilterTwo:"+request.getMessage()); filterChain.doFilter(request,response,filterChain); System.out.println("FilterTwo:"+response.getMessage()); } }
......FilterThree、FilterFour、FilterFive
- 定义一个处理器链(实现Filter接口是为了实现嵌套用法,简单用法不需要实现)
public class FilterChain implements Filter{
//用于存储处理器 private List<Filter> list = new ArrayList<>();
//索引 private int index = 0; //可以根据需求拓展处理器 public FilterChain addList(Filter filter) { list.add(filter); return this; } public void doFilter(Request request, Response response, FilterChain filterChain) { if(list.size()<=index) return; Filter f = list.get(index); index++;
//当FilterChain嵌套另一个FilterChain时需要传入this,完成FilterChain调用的转换 f.doFilter(request,response,this); } }
测试:
本例中FilterChain嵌套FilterChain,若难以理解,可以不嵌套(忽略-------以下代码),直接运行filterChain2.doFilter完成一个简单的责任链调用。
@Test public void testFilter(){ //请求和响应都是一个字符串 Request request = new Request(); request.setMessage("requestMsg"); Response response = new Response(); response.setMessage("responseMsg"); //将处理器one,two,three加入filterChain2 FilterChain filterChain2 = new FilterChain(); filterChain2.addList(new FilterOne()).addList(new FilterTwo()).addList(new FilterThree());
//--------------------------- //将处理器four,five加入filterChain1,并将filterChain2也加入filterChain1,注意:这个责任链也实现了Filter接口,因此也可以加入责任链,且必须在所有处理器最后加入因为: //f.doFilter(request,response,this);filterChain调用最后一个处理器的时候也就是另一个filterChain的doFilter传入的this将是另一个filterChain的引用。 FilterChain filterChain1 = new FilterChain(); filterChain1.addList(new FilterFour()).addList(new FilterFive()).addList(filterChain2); filterChain1.doFilter(request,response,filterChain1); }
结果
FilterFour:requestMsg
FilterFive:requestMsg
FilterOne:requestMsg
FilterTwo:requestMsg
FilterThree:requestMsg
FilterThree:responseMsg
FilterTwo:responseMsg
FilterOne:responseMsg
FilterFive:responseMsg
FilterFour:responseMsg