环境: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
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实现原理
当前URL:http://www.shufengxianlan.com/qtweb/news42/318742.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联