- SpringMVC-HandlerExecutionChain 类就使用到职责链模式
| public class DispatcherServlet extends FrameworkServlet { |
| protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception { |
| HttpServletRequest processedRequest = request; |
| HandlerExecutionChain mappedHandler = null; |
| boolean multipartRequestParsed = false; |
| mappedHandler = getHandler(processedRequest); |
| HandlerExecutionChain |
| |
| if (!mappedHandler.applyPreHandle(processedRequest, response)) { |
| return; |
| } |
| mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); |
| |
| mappedHandler.applyPostHandle(processedRequest, response, mv); |
| processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException); |
| triggerAfterCompletion(processedRequest, response, mappedHandler, ex); |
| |
| public class HandlerExecutionChain { |
| boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception { |
| |
| |
| } |
| void applyPostHandle(HttpServletRequest request, HttpServletResponse response, ModelAndView mv) throws Exception { |
| |
| } |
| void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, Exception ex){ |
| |
| |
| } |
| } |
| 1) springmvc 请求的流程图中,执行了 拦截器相关方法 interceptor.preHandler 等等 |
| 2) 在处理SpringMvc请求时,使用到职责链模式还使用到适配器模式 |
| 3) HandlerExecutionChain 主要负责的是请求拦截器的执行和请求处理,但是他本身不处理请求,只是将请求分配给链上注册处理器执行,这是职责链实现方式,减少职责链本身与处理逻辑之间的耦合,规范了处理流程 |
| 4) HandlerExecutionChain 维护了 HandlerInterceptor 的集合, 可以向其中注册相应的拦截器 |
| 1) 将请求和处理分开,实现解耦,提高系统的灵活性 |
| 2) 简化了对象,使对象不需要知道链的结构 |
| 3) 性能会受到影响,特别是在链比较长的时候,因此需控制链中最大节点数量,一般通过在Handler中设置一个最大节点数量,在setNext()方法中判断是否已经超过阀值,超过则不允许该链建立,避免出现超长链无意识地破坏系统性能 |
| 4) 调试不方便。采用了类似递归的方式,调试时逻辑可能比较复杂 |
| 5) 最佳应用场景:有多个对象可以处理同一个请求时,比如:多级请求、请假/加薪等审批流程、Java Web中Tomcat对Encoding的处理、拦截器 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?