这篇文章主要讲解了“Servlet中Filter的实现原理是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Servlet中Filter的实现原理是什么”吧!
环境: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不也是这样么!!!
感谢各位的阅读,以上就是“Servlet中Filter的实现原理是什么”的内容了,经过本文的学习后,相信大家对Servlet中Filter的实现原理是什么这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。