责任链,顾名思义,就是用来处理相关事务责任的一条执行链,执行链上有多个节点,每个节点都有机会(条件匹配)处理请求事务,如果某个节点处理完了就可以根据实际业务需求传递给下一个节点继续处理或者返回处理完毕。

应用场景

  1. http的过滤器filter以及filterChain,过滤来自用户的request和来自服务器的response
  2. 请假的OA申请,请假天数如果是半天到1天,可能直接主管批准即可;

如果是1到3天的假期,需要部门经理批准;
如果是3天到30天,则需要总经理审批;
大于30天,正常不会批准。

image.png
模拟http中的FilterChain

  1. package com.mashibing.dp.cor.servlet.v4;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. public class Servlet_Main {
  5. public static void main(String[] args) {
  6. //模拟httpServletRequest
  7. Request request = new Request();
  8. request.str = "大家好:),<script>,欢迎访问 mashibing.com ,大家都是996 ";
  9. //模拟httpServletResponse
  10. Response response = new Response();
  11. response.str = "response";
  12. FilterChain chain = new FilterChain();
  13. chain.add(new HTMLFilter()).add(new SensitiveFilter());
  14. chain.doFilter(request, response);
  15. System.out.println(request.str);
  16. System.out.println(response.str);
  17. }
  18. }
  19. /**
  20. * 过滤器
  21. */
  22. interface Filter {
  23. void doFilter(Request request, Response response, FilterChain chain);
  24. }
  25. /**
  26. * 过滤器实现类一
  27. */
  28. class HTMLFilter implements Filter {
  29. @Override
  30. public void doFilter(Request request, Response response, FilterChain chain) {
  31. //将<>过滤为[]
  32. request.str = request.str.replaceAll("<", "[").replaceAll(">", "]") + "HTMLFilter()";
  33. chain.doFilter(request, response);
  34. response.str += "--HTMLFilter()";
  35. }
  36. }
  37. class Request {
  38. String str;
  39. }
  40. class Response {
  41. String str;
  42. }
  43. /**
  44. * 过滤器实现类二
  45. */
  46. class SensitiveFilter implements Filter {
  47. @Override
  48. public void doFilter(Request request, Response response, FilterChain chain) {
  49. //将996过滤为955
  50. request.str = request.str.replaceAll("996", "955") + " SensitiveFilter()";
  51. chain.doFilter(request, response);
  52. response.str += "--SensitiveFilter()";
  53. }
  54. }
  55. /**
  56. * 过滤器链,存放所有需要用到的过滤器
  57. */
  58. class FilterChain {
  59. List<Filter> filters = new ArrayList<>();
  60. int index = 0;
  61. public FilterChain add(Filter f) {
  62. filters.add(f);
  63. return this;
  64. }
  65. public void doFilter(Request request, Response response) {
  66. if(index == filters.size()) return;
  67. //依次执行各个过滤器
  68. Filter f = filters.get(index);
  69. index ++;
  70. f.doFilter(request, response, this);
  71. }
  72. }