标签:finally isa end bean creating str occurs chain 客户端
做后台的,Filter肯定没少配置,但是知晓其原理的可能不多。在这之前我也不懂,但这并不影响业务开发,同时也有其他的知识要学,所以一直就没看。这阵子有点闲,刚好在看《How Tomcat Works》的PipeLine相关内容。索性好好梳理一下FilterChain相关的知识。
顾名思义,FilterChain就是一条过滤链。其中每个过滤器(Filter)都可以决定是否执行下一步。
过滤分两个方向,进和出:
进:在把ServletRequest和ServletResponse交给Servlet的service方法之前,需要进行过滤
出:在service方法完成后,往客户端发送之前,需要进行过滤
定义
一般,我们定义Filter类一般通过实现Filter接口来完成,然后在doFilter方法中编写自己的过滤逻辑。由于方法参数中有Filter对象所在FilterChain的引用,故可以控制过滤链的进行。但控制内容,只能是
1.向下执行
2.不向下执行。
配置
在老项目中,一般直接在web.xml文件中配置。利用<filter></filter>配置过滤器名称,类以及过滤器在链中的位置。
而在Spring Boot项目中,则可以通过FilterRegisterBean来配置过滤器。
FilterChain的实现类是上图中的ApplicationFilterChain。一个ApplicationFilterChain对象包含几个主要参数
很多人,可能会疑惑,FilterChain是如何实现向下执行的。其实看到上面那些参数,你估计就已经明白了。即FilterChain持有所有Filter对象到一个数组中,然后通过移动pos,来获取后续的Filter并执行的。
触发方式:由上一个执行的Filter调用FilterChain的doFilter方法。
以下是ApplicationFilterChain的doFilter和internalDoFilter方法。
/** * Invoke the next filter in this chain, passing the specified request * and response. If there are no more filters in this chain, invoke * the <code>service()</code> method of the servlet itself. * * @param request The servlet request we are processing * @param response The servlet response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet exception occurs */ @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; try { java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction<Void>() { @Override public Void run() throws ServletException, IOException { internalDoFilter(req,res); return null; } } ); } catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); } } else { internalDoFilter(request,response); } } private void internalDoFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { // Call the next filter if there is one if (pos < n) { ApplicationFilterConfig filterConfig = filters[pos++]; try { Filter filter = filterConfig.getFilter(); if (request.isAsyncSupported() && "false".equalsIgnoreCase( filterConfig.getFilterDef().getAsyncSupported())) { request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE); } if( Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; Principal principal = ((HttpServletRequest) req).getUserPrincipal(); Object[] args = new Object[]{req, res, this}; SecurityUtil.doAsPrivilege ("doFilter", filter, classType, args, principal); } else { filter.doFilter(request, response, this); } } catch (IOException | ServletException | RuntimeException e) { throw e; } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); throw new ServletException(sm.getString("filterChain.filter"), e); } return; } // We fell off the end of the chain -- call the servlet instance try { if (ApplicationDispatcher.WRAP_SAME_OBJECT) { lastServicedRequest.set(request); lastServicedResponse.set(response); } if (request.isAsyncSupported() && !servletSupportsAsync) { request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE); } // Use potentially wrapped request from this point if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse) && Globals.IS_SECURITY_ENABLED ) { final ServletRequest req = request; final ServletResponse res = response; Principal principal = ((HttpServletRequest) req).getUserPrincipal(); Object[] args = new Object[]{req, res}; SecurityUtil.doAsPrivilege("service", servlet, classTypeUsedInService, args, principal); } else { servlet.service(request, response); } } catch (IOException | ServletException | RuntimeException e) { throw e; } catch (Throwable e) { e = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(e); throw new ServletException(sm.getString("filterChain.servlet"), e); } finally { if (ApplicationDispatcher.WRAP_SAME_OBJECT) { lastServicedRequest.set(null); lastServicedResponse.set(null); } } }
看到上面移动pos(本质上就是++操作),估计有人会跟我一样想到线程安全问题,即FilterChain是否会存在多线程访问的情况。如果存在多线程访问,由于每个线程的过滤进度可能都不一样,必然会互相干扰。
答案是这样,每个请求都会创建一个新的FilterChain对象。
注意:Filter配置是针对整个Web项目的,而每个FilterChain对象是针对每个请求的。
我是怎么知道的?
猜测加验证。即定位ApplicationFilterChain的创建操作即可。ApplicationFilterChain对象由ApplicationFilterFactory工厂的createFilterChain方法生成。而这个方法在ApplicationDispatcher的invoke方法内被调用。而这个invoke方法是Connector把新请求传递给Container的方式。
FilterChain就是典型的责任链模式的实现案例。类似的还有,Tomcat的Pipeline Task,Netty的ChannelPipeline.
标签:finally isa end bean creating str occurs chain 客户端
原文地址:https://www.cnblogs.com/longfurcat/p/10574734.html