环境:Java8
Servlet中Filter使用的设计模式是责任链设计模式。我们可以定义一组Filter然后对数据进行依次的处理。责任链设计模式属于行为型模式。UML图如下:
Filter执行流程如下:
接下来我们来实现一个Filter
Filter.java接口
- public interface Filter {
- void doFilter(Request request, Response response, FilterChain chain) ;
- }
FilterChain.java 关键的调用链
- public class FilterChain implements Filter{
- private List<Filter> filters = new ArrayList<>() ;
- private int position = 0 ;
- public void doFilter(Request request, Response response, FilterChain chain) {
- if (position > filters.size() - 1) {
- return ;
- }
- Filter filter = filters.get(this.position++) ;
- filter.doFilter(request, response, this) ;
- }
- // 构建需要调用的Filter链
- public FilterChain addFilter(Filter filter) {
- this.filters.add(filter) ;
- return this ;
- }
- }
Filter相关子类
- public class LoginFilter implements Filter {
- @Override
- public void doFilter(Request request, Response response, FilterChain chain) {
- System.out.println("LoginFilter entry...") ;
- chain.doFilter(request, response, chain) ;
- System.out.println("LoginFilter over...") ;
- }
- }
- public class CharFilter implements Filter {
- @Override
- public void doFilter(Request request, Response response, FilterChain chain) {
- System.out.println("CharFilter entry...") ;
- chain.doFilter(request, response, chain) ;
- System.out.println("CharFilter over...") ;
- }
- }
- public class GrantFilter implements Filter {
- @Override
- public void doFilter(Request request, Response response, FilterChain chain) {
- System.out.println("GrantFilter entry...") ;
- chain.doFilter(request, response, chain) ;
- System.out.println("GrantFilter over...") ;
- }
- }
客户端
- public static void main(String[] args) {
- LoginFilter loginFilter = new LoginFilter() ;
- CharFilter charFilter = new CharFilter() ;
- GrantFilter grantFilter = new GrantFilter() ;
- FilterChain chain = new FilterChain() ;
- chain.addFilter(loginFilter).addFilter(charFilter).addFilter(grantFilter) ;
- Request request = new Request() ;
- Response response = new Response() ;
- chain.doFilter(request, response, null) ;
- }
运行结果
按照添加Filter顺序,请求时先添加的先执行,返回时后添加的Filter先执行。java web中的Filter不也是这样么!!!