过滤器设计模式
过滤器设计模式:按照指定的顺序进行过滤,由一个过滤器链接口,一个起切换作用的过滤器链接口实现类,若干个过滤器链接口实现类,一个过滤器链适配器类组成。
过滤器链接口:
package com.example.ssm.filter; import javax.servlet.http.HttpServletRequest; /** * 过滤器链接口 */ public interface FilterChain { void doFilter(HttpServletRequest request, FilterChain chain); }
起切换作用的过滤器链接口实现类:
package com.example.ssm.filter; import com.google.common.collect.Lists; import org.springframework.util.CollectionUtils; import javax.servlet.http.HttpServletRequest; import java.util.List; /** * 主过滤器链,起衔接作用 */ public class MainChain implements FilterChain { private List<FilterChain> filterChains = Lists.newArrayList(); private int index = 0; @Override public void doFilter(HttpServletRequest request, FilterChain chain) { if (CollectionUtils.isEmpty(filterChains)) { return; } FilterChain filterChain = filterChains.get(index++); filterChain.doFilter(request, chain); } public void addFilter(FilterChain chain) { filterChains.add(chain); } }
若干个过滤器链实现类:
package com.example.ssm.filter; import javax.servlet.http.HttpServletRequest; /** * 第一个过滤器链 */ public class FirstChain implements FilterChain { @Override public void doFilter(HttpServletRequest request, FilterChain chain) { System.out.println("first step"); chain.doFilter(request,chain); System.out.println("five step"); } }
package com.example.ssm.filter; import javax.servlet.http.HttpServletRequest; /** * 第二个过滤器链 */ public class TwoChain implements FilterChain { @Override public void doFilter(HttpServletRequest request, FilterChain chain) { System.out.println("two step"); chain.doFilter(request,chain); System.out.println("four step"); } }
package com.example.ssm.filter; import javax.servlet.http.HttpServletRequest; /** * 第三个过滤器链 * 最后的过滤器链类中doFilter方法里不要调用chain.doFilter方法 */ public class ThreeChain implements FilterChain { @Override public void doFilter(HttpServletRequest request, FilterChain chain) { System.out.println("Three step"); } }
过滤器链适配器类:
package com.example.ssm.filter; /** * 过滤器链适配器 */ public class Adapter { private void executeChain() { MainChain mainChain = new MainChain(); mainChain.addFilter(new FirstChain()); mainChain.addFilter(new TwoChain()); mainChain.addFilter(new ThreeChain()); System.out.println("过滤器执行开始"); mainChain.doFilter(null, mainChain); System.out.println("过滤器执行结束"); } public static void main(String[] args) { new Adapter().executeChain(); } }
程序运行结果:
过滤器执行开始
first step
two step
Three step
four step
five step
过滤器执行结束