责任链,顾名思义,就是用来处理相关事务责任的一条执行链,执行链上有多个节点,每个节点都有机会(条件匹配)处理请求事务,如果某个节点处理完了就可以根据实际业务需求传递给下一个节点继续处理或者返回处理完毕。
应用场景
- http的过滤器filter以及filterChain,过滤来自用户的request和来自服务器的response
- 请假的OA申请,请假天数如果是半天到1天,可能直接主管批准即可;
如果是1到3天的假期,需要部门经理批准;
如果是3天到30天,则需要总经理审批;
大于30天,正常不会批准。
模拟http中的FilterChain
package com.mashibing.dp.cor.servlet.v4;
import java.util.ArrayList;
import java.util.List;
public class Servlet_Main {
public static void main(String[] args) {
//模拟httpServletRequest
Request request = new Request();
request.str = "大家好:),<script>,欢迎访问 mashibing.com ,大家都是996 ";
//模拟httpServletResponse
Response response = new Response();
response.str = "response";
FilterChain chain = new FilterChain();
chain.add(new HTMLFilter()).add(new SensitiveFilter());
chain.doFilter(request, response);
System.out.println(request.str);
System.out.println(response.str);
}
}
/**
* 过滤器
*/
interface Filter {
void doFilter(Request request, Response response, FilterChain chain);
}
/**
* 过滤器实现类一
*/
class HTMLFilter implements Filter {
@Override
public void doFilter(Request request, Response response, FilterChain chain) {
//将<>过滤为[]
request.str = request.str.replaceAll("<", "[").replaceAll(">", "]") + "HTMLFilter()";
chain.doFilter(request, response);
response.str += "--HTMLFilter()";
}
}
class Request {
String str;
}
class Response {
String str;
}
/**
* 过滤器实现类二
*/
class SensitiveFilter implements Filter {
@Override
public void doFilter(Request request, Response response, FilterChain chain) {
//将996过滤为955
request.str = request.str.replaceAll("996", "955") + " SensitiveFilter()";
chain.doFilter(request, response);
response.str += "--SensitiveFilter()";
}
}
/**
* 过滤器链,存放所有需要用到的过滤器
*/
class FilterChain {
List<Filter> filters = new ArrayList<>();
int index = 0;
public FilterChain add(Filter f) {
filters.add(f);
return this;
}
public void doFilter(Request request, Response response) {
if(index == filters.size()) return;
//依次执行各个过滤器
Filter f = filters.get(index);
index ++;
f.doFilter(request, response, this);
}
}