模仿javax包下的Filter和FilterChain

接上上次的责任链模式尾巴,以下代码是仿javax包中的Filter和FilterChain

请求流程图:

U_JAK__`5_SPYPE~T`2VJZ5.png

1
2
3
public interface Filter {
void doFilter(Request request,Response response,FilterChain chain);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class FilterChain {
List<Filter> filters = new ArrayList<>();
int index = 0;

public FilterChain add(Filter filter){
filters.add(filter);
return this;
}

public void doFilter(Request request,Response response,FilterChain chain){
if(index == filters.size()){
return;
}
Filter filter = filters.get(index);
index++;
filter.doFilter(request,response,chain);
}
}
1
2
3
4
5
6
7
8
9
@Data
public class Request {
private String str;
}
-----------------------------
@Data
public class Response {
private String str;
}
1
2
3
4
5
6
7
8
9
public class HTMLFilter implements Filter {
@Override
public void doFilter(Request request,Response response,FilterChain chain) {
request.setStr(request.getStr().replaceAll("<", "[").replaceAll(">", "]"));
System.out.println("HTMLFilter(request)");
chain.doFilter(request,response,chain);
response.setStr(response.getStr() + "--- HTMLFilter...");
}
}
1
2
3
4
5
6
7
8
9
public class SensitiveFilter implements Filter {
@Override
public void doFilter(Request request,Response response,FilterChain chain) {
request.setStr(request.getStr().replaceAll("996", "955"));
System.out.println("SensitiveFilter(request)");
chain.doFilter(request,response,chain);
response.setStr(response.getStr() + "--- SensitiveFilter...");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Main {
public static void main(String[] args) {
Request request = new Request();
Response response = new Response();
response.setStr("response");
request.setStr("大家好:),<script>,欢迎访问www.oldman.run,大家都是996");
FilterChain chain = new FilterChain();
chain.add(new HTMLFilter()).add(new SensitiveFilter());
chain.doFilter(request,response,chain);
System.out.println(request.getStr());
System.out.println(response.getStr());
}
}

执行结果:

1
2
3
4
HTMLFilter(request)
SensitiveFilter(request)
大家好:),[script],欢迎访问www.oldman.run,大家都是955
response--- SensitiveFilter...--- HTMLFilter...

从结果中可以看到整个request和response的执行顺序,去是1->2,回来是2->1。