Struts2初始化之Dispatcher

【PCL】SolidWorks 三维建模 STL, OBJ 采样生成 PCD 点云数据(附源码) [PCL自学篇] 一.SolidWorks三维建模STL,OBJ采样生成PCD点云数据新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML 图表FLowchart流程图导出与导入导出导入 这阵子做线结构光视觉检测(轨道)项目的过程中,发现之前的许多知识点在逐渐遗忘,常言好记性 阅读详情

Dispatcher也叫做核心分发器,Dispatcher类负责整个Struts2项目的初始化工作。这是一个很庞大的类,这里会挑选一些重要的方法进行分析。
很明显这是一个应用ThreadLocal的例子,它为当前线程中的一个叫做ThreadLocalMap的线程副本,使得线程与线程之间,每一个线程可以独立的修改自己的副本,而不会影响到其他线程的变量,从而使线程安全。
Dispatcher分发器的出现,作用是由刚刚处理过Http请求,并完成初始化后的struts2部分转入xwork部分。

   private static ThreadLocal<Dispatcher> instance = new ThreadLocal<Dispatcher>();

初始化国际化方法

  @Inject(value=StrutsConstants.STRUTS_LOCALE, required=false)
    public void setDefaultLocale(String val) {
        defaultLocale = val;
    }
 @Inject(StrutsConstants.STRUTS_I18N_ENCODING)
    public void setDefaultEncoding(String val) {
        defaultEncoding = val;
    }

cleanup()方法,清除当前线程之中的对象实例,清空拦截器栈等。

 public void cleanup() {

        // clean up ObjectFactory
        //清除对象实例
        ObjectFactory objectFactory = getContainer().getInstance(ObjectFactory.class);
        if (objectFactory == null) {
            if (LOG.isWarnEnabled()) {
            LOG.warn("Object Factory is null, something is seriously wrong, no clean up will be performed");
            }
        }
        if (objectFactory instanceof ObjectFactoryDestroyable) {
            try {
                ((ObjectFactoryDestroyable)objectFactory).destroy();
            }
            catch(Exception e) {
                // catch any exception that may occurred during destroy() and log it
                LOG.error("exception occurred while destroying ObjectFactory [#0]", e, objectFactory.toString());
            }
        }

          //将当前分发器的引用置为null
        instance.set(null);

          //销毁Dispatcher监听器
        if (!dispatcherListeners.isEmpty()) {
            for (DispatcherListener l : dispatcherListeners) {
                l.dispatcherDestroyed(this);
            }
        }

        // clean up all interceptors by calling their destroy() method
        Set<Interceptor> interceptors = new HashSet<Interceptor>();
        Collection<PackageConfig> packageConfigs = configurationManager.getConfiguration().getPackageConfigs().values();
        for (PackageConfig packageConfig : packageConfigs) {
            for (Object config : packageConfig.getAllInterceptorConfigs().values()) {
                if (config instanceof InterceptorStackConfig) {
                    for (InterceptorMapping interceptorMapping : ((InterceptorStackConfig) config).getInterceptors()) {
                        interceptors.add(interceptorMapping.getInterceptor());
                    }
                }
            }
        }
        //清空拦截器栈
        for (Interceptor interceptor : interceptors) {
            interceptor.destroy();
        }

        // Clear container holder when application is unloaded / server shutdown
        ContainerHolder.clear();
        //销毁ActionContext
        ActionContext.setContext(null);

        // clean up configuration
        configurationManager.destroyConfiguration();
        configurationManager = null;
    }

Dispatcher最重要的方法就是init(),初始化方法。

  public void init() {
//判断ConfigurationManager对象是否为null,如果为null,new一个
        if (configurationManager == null) {
            configurationManager = createConfigurationManager(BeanSelectionProvider.DEFAULT_BEAN_NAME);
        }

        try {
        //对配置文件进行初始化
            init_FileManager();
            //default.properties初始化
            init_DefaultProperties(); // [1]
            //xwork配置文件的初始化
            init_TraditionalXmlConfigurations(); // [2]

            init_LegacyStrutsProperties(); // [3]
            init_CustomConfigurationProviders(); // [5]
            init_FilterInitParameters() ; // [6]
            init_AliasStandardObjects() ; // [7]
            //初始化国际化
            Container container = init_PreloadConfiguration();
            //注入容器,container
            container.inject(this);
            init_CheckWebLogicWorkaround(container);

            if (!dispatcherListeners.isEmpty()) {
                for (DispatcherListener l : dispatcherListeners) {
                    l.dispatcherInitialized(this);
                }
            }
        } catch (Exception ex) {
            if (LOG.isErrorEnabled())
                LOG.error("Dispatcher initialization failed", ex);
            throw new StrutsException(ex);
        }
    }

serviceAction()方法,这个方法也是执行action的主要流程的方法

  public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,
                              ActionMapping mapping) throws ServletException {
//创建action对应的上下文映射,在我看来是一种封装
        Map<String, Object> extraContext = createContextMap(request, response, mapping, context);

        // If there was a previous value stack, then create a new copy and pass it in to be used by the new Action
        //获取值栈
        ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);
        boolean nullStack = stack == null;
        if (nullStack) {
        //创建ActionContext,也就是我们所说的上下文
            ActionContext ctx = ActionContext.getContext();
            if (ctx != null) {
                stack = ctx.getValueStack();
            }
        }
        if (stack != null) {
        //将action对应的映射压入值栈
            extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.createValueStack(stack));
        }

        String timerKey = "Handling request from Dispatcher";
        try {
            UtilTimerStack.push(timerKey);
            //获取action的信息,action名,方法等
            String namespace = mapping.getNamespace();
            String name = mapping.getName();
            String method = mapping.getMethod();

            Configuration config = configurationManager.getConfiguration();
            //利用容器创建实例,动态的创建代理
            ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(
                    namespace, name, method, extraContext, true, false);

            request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack());

            // if the ActionMapping says to go straight to a result, do it!
            //拦截器执行完毕后返回的resultCode如果不为null,就执行结果集
            if (mapping.getResult() != null) {
                Result result = mapping.getResult();
                result.execute(proxy.getInvocation());
            } else {
            //执行完结果集后执行execute()方法
                proxy.execute();
            }

            // If there was a previous value stack then set it back onto the request
            if (!nullStack) {
                request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);
            }
        } catch (ConfigurationException e) {
            // WW-2874 Only log error if in devMode
            if (devMode) {
                String reqStr = request.getRequestURI();
                if (request.getQueryString() != null) {
                    reqStr = reqStr + "?" + request.getQueryString();
                }
                LOG.error("Could not find action or result\n" + reqStr, e);
            } else {
                if (LOG.isWarnEnabled()) {
                    LOG.warn("Could not find action or result", e);
                }
            }
            sendError(request, response, context, HttpServletResponse.SC_NOT_FOUND, e);
        } catch (Exception e) {
            if (handleException || devMode) {
                sendError(request, response, context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
            } else {
                throw new ServletException(e);
            }
        } finally {
            UtilTimerStack.pop(timerKey);
        }
    }

wrapRequest()方法,是对HttpServletRequest 类型的请求进行包装,应用了装饰器模式,目的是将Http服务端与初始化解耦,将其分离

 public HttpServletRequest wrapRequest(HttpServletRequest request, ServletContext servletContext) throws IOException {
        // don't wrap more than once
        if (request instanceof StrutsRequestWrapper) {
            return request;
        }

        String content_type = request.getContentType();
        if (content_type != null && content_type.contains("multipart/form-data")) {
            MultiPartRequest mpr = getMultiPartRequest();
            LocaleProvider provider = getContainer().getInstance(LocaleProvider.class);
            request = new MultiPartRequestWrapper(mpr, request, getSaveDir(servletContext), provider);
        } else {
            request = new StrutsRequestWrapper(request, disableRequestAttributeValueStackLookup);
        }

        return request;
    }

createContextMap()方法,创建上下文映射,并将其压栈

 public Map<String,Object> createContextMap(HttpServletRequest request, HttpServletResponse response,
            ActionMapping mapping, ServletContext context) {

        // request map wrapping the http request objects
        Map requestMap = new RequestMap(request);

        // parameters map wrapping the http parameters.  ActionMapping parameters are now handled and applied separately
        Map params = new HashMap(request.getParameterMap());

        // session map wrapping the http session
        Map session = new SessionMap(request);

        // application map wrapping the ServletContext
        Map application = new ApplicationMap(context);

        Map<String,Object> extraContext = createContextMap(requestMap, params, session, application, request, response, context);

        if (mapping != null) {
            extraContext.put(ServletActionContext.ACTION_MAPPING, mapping);
        }
        return extraContext;
    }

其余的方法是对,上传下载,对容器,上下文,值栈的初始化,以及国际化,字符编码的初始化。

【Arduino 动手做】构建一个迷你 Las Vegas RGB LED 球体 《Arduino迷你拉斯维加斯球体项目:15岁少年的创意挑战》 15岁的Ben通过本项目展示了如何利用Arduino平台制作一个经济实惠的迷你拉斯维加斯球体夜灯。该项目涉及LED选择(采用WS2812B可编程灯带)、电子元件配置(含Arduino Nano微控制器和红外遥控)以及3D建模设计(100毫米直径球体)。项目难点包括LED布局优化、供电方案设计和3D打印外壳制作。Ben详细记录了从背景研究、电路设计到最终实现的完整过程,特别强调了分辨率与成本的平衡,以及如何通过白色扩散器改善视觉效果。这个项目不仅 阅读详情

相关推荐

Intel FPGA 开发工具 Quartus/ModelSim 20.1.1 安装

Lite版本是免费的。 官网下载地址:Download Center for FPGAs 官网下载需要注册账号,这里也把下图中的所有文件都放到百度网盘。 百度网盘: 链接: https://pan.baidu.com/s/1F8lg2XKMZarDUebpo7ki9Q 提取码: 2333 只需要把主程序、ModelSim和选择的FPGA器件放到同一个目录,然后双击主程序的安装包,就会把其他的加载了,如下图。 如果需要更详细的安装步骤,可参考:Quartus Prime 19.1版本精简版下载安装教程_

hujy23的博客 1万+

struts2_源码学习_Dispatcher(1)

续Logging System 目录 Dispatcher 第一步:创建ConfigurationManager。 第二步:往ConfigurationManager添加一个FileManagerProvider 第三步:往ConfigurationManager添加一个DefaultPropertiesProvider 第四步:往ConfigurationManager添加一个Str...

Onion的博客 568

三甲医院网络架构与安全建设实战

华为OceanStor] [华为OceanStor][PACS存储双活] [HIS数据库同步]患者隐私 数据脱敏 天清Web防火墙动态脱敏策略。主数据中心 --[OTV专线]-- 备数据中心。实现医疗业务网/卫生专网/互联网三网隔离。核心业务配置(华为CE6865)自动备份配置(每天02:00)安全事件响应(30分钟SLA)漏洞扫描(每周日00:00)实现医疗物联网统一接入管控。五、等保2.0合规关键配置。堡垒机登录(双因素认证)四、医疗物联网安全方案。

有小小的远大抱负 1917

struts2架构中核心对象的探索—— Dispatcher&ConfigurationProvider

首先强调一下struts2的线程程安全,在Struts2中大量采用ThreadLocal线程局部变量的方法来保证线程的安全,像Dispatcher等都是通过ThreadLocal来保存变量值,使得每个线程都有自己独立的实例变量,互不相干。 接下来就从Dispatcher开始看起,先看其构造函数: //创建Dispatcher,此类是一个Delegate,它是真正完成根据url解析转向

码上学习 393

开源WorkBuddy实战课:从零搭建AI Agent办公自动化工作台

AI Agent作为大语言模型之上的智能体,正在重塑办公效率。它通过工具调用、任务规划与长期记忆,将被动问答升级为主动执行。WorkBuddy作为图形化智能体工作台,降低了搭建门槛,让非技术人员也可配置自动化流程。本文开源整套实战资料,涵盖JDK环境配置、模型接入、日报邮件处理、表格清洗、批量文档生成等场景,并讲解自定义指令、Skills扩展与MCP协议。从基础概念到工程实践,帮助读者快速上手,构建属于自己的办公自动化助手。

weixin_29083475的博客 236

2024最新超详细无痛安装PyTorch,包括下载地址、环境配置与各种避坑指南

PyTorch更新很快,2024最新下载安装经验贴,包括anaconda+CUDA+cuDNN+PyTorch四部分的下载和安装。文章详细介绍了下载地址、环境配置、虚拟环境建立的问题,还温馨提示了各种闭坑指南。有需要的友友快过来康康!

qq_43596278的博客 11万+

Struts|Struts返回结果类型(dispatcher,redirect,redirectAction)及全局result探究

Struts|Struts返回结果类型(dispatcher,redirect,redirectAction)及全局result探究。工作之后再也没用过了,^_^,致我们逝去的青春。

不甩锅的码农 2936

手机抽奖页面代码html,html5大转盘抽奖支持手机转盘抽奖代码

特效描述:html5 大转盘抽奖 支持手机 转盘抽奖代码。html5转盘,html5抽奖,手机转盘,手机抽奖,手机转盘抽奖,可配置奖品抽奖。代码结构1. 引入CSS2. 引入JS3. HTML代码大转盘活动var turnplate={restaraunts:[],//大转盘奖品名称colors:[],//大转盘奖品区块对应背景颜色outsideRadius:192,//大转盘外圆的半径textR...

weixin_39628551的博客 1889

struts2--Dispatcher

public class Dispatcher{ //提供了一个静态的ThreadLocal变量 private static ThreadLocal instance=new ThreadLocal(); //提供一个接口方法,用于获得当前线程安全的Dispatcher实例 public static Dispatcher getInstance(){ return instance

yansuoo的博客 840

【CANdelaStudio编辑CDD】-2.2-给$27服务SecurityAccess创建一个SecurityLevel安全级别并修改SecurityAccess安全访问状态机(UDS诊断)

前一篇: 【UDS诊断描述文件CDD】-2.1-ISO_14229中$27服务理论部分https://blog.csdn.net/qfmzhu/article/details/120392660 案例背景: 在CDD中如何给$27服务创建一个新的SecurityLevel安全级别; 在CDD中如何给$27服务修改SecurityAccess安全访问状态机。 1 查看$27服务中已有的SecurityLevel安全级别 2 查看$27服务中已有的SecurityAccess安全...

「汽车电子助手」的博客 4663

YOLOv5源码逐行超详细注释与解读(2)——推理部分detect.py

全网最详细的YOLOv5之推理部分detect.py源码逐行注释,近四万字的超详细讲解!小白入门必看!

路人贾的博客 5万+

struts2源码探索1

package org.apache.struts2.dispatcher.FilterDispatcher中的一个方法createDispatcher,看这个for循环   看了这个for循环顿时感觉自己的代码水平真的有待提高   protected Dispatcher createDispatcher(FilterConfig filterConfig) { ...

腾飞FLY 129

高通Camx功能feature分析之一:remosaic功能导通

本文详细介绍了S5K3P9S传感器前置场景中SW Remosaic功能的实现流程。首先需在sensorxml中确认支持SW Remosaic类型,并集成remosaic相关库文件(libremosaic_wrapper.so等)。核心实现包括:初始化阶段调用InitFrontSamsungRemosaic();执行线程DeferFrontInitThread()读取校准数据;通过DoSamsungRemosaic()执行remosaic算法处理;最后在析构函数中调用DeinitFrontSamsungRem

1716

struts2源码分析(二)(初始化)

2、Dispatcher dispatcher = init.initDispatcher(config);  这行代码是struts2初始化的核心部分(该方法是InitOperations中的方法)方法的具体内容如下:  1:Dispatcher dispatcher = createDipatcher(filterConfig); /** * 创建一个dispatcher实

sjcawn的专栏 1382

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

STRUTS2中报:The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the associated filter.

此错误的产生,一般是因为在web.xml中配置的struts2过滤器中             org.apache.struts2.dispatcher.FilterDispatcher         org.apache.struts2.dispatcher.FilterDispatcher                 org.apache.struts2

1万+

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

朝花夕拾之Struts2的StrutsPrepareAndExecuteFilter的初始化过程

在使用Struts2的时候,我们都会在项目中的web.xml这样定义: <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteF...

aaabc1112345的博客 289

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

struts2+json的几个错误

今晚碰到的几个错误,经百度+谷歌+分析,正确解决了,贴出来供其他人参考一下  ps:浪费在这些错误-解决错误的时间好多撒,java 程序媛伤不起哦....... /-|-\ 准备工作: 把strus2+json整合的jar包复制到     /项目名/WebRoot/WEB-INF/lib中,如下图: 之前运行好好的,动了一下代码就冒出来这么多错误,如下所示: 1. Disp

luoxia0805的专栏 1528

struts2访问JSP页面404的问题

action标签中class属性对应类不存在,原因可能是手误写错,或者还没开始写action就配置了struts.xml 运行结果 报错原因是web.xml中的过滤器过滤了所有请求。在创建Dispatcher,会读取 filterConfig 中的配置信息,将配置信息解析出来,封装成为一个Map,然后根绝servlet上下文和参数Map构造Dispatcher 。Dispatcher初始...

农夫阿才 1542

Struts2错误:The Struts dispatcher cannot be found.

如果你在配置struts2如果出现下列问题 [code="java"]The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has ...

zwdsmileface的专栏 216

Struts2源码粗略分析二:初始化详解

分析初始化部分,阅读时最好一边读一边debug,这样理解更清楚更深刻!

KNIGHTRCOM(rcom10002的专栏) 2632

Struts2中出现 Dispatcher initialization failed错误

 在尝试搭建Struts2框架的时候出现该以下问题 Dispatcher initialization failed Unable to load configuration. - bean - jar:file:/D:/Workspaces/MyEclipse%208.6/.metadata/.me_tcat/webapps/demo/WEB-INF/lib/struts2-gxp-p

技术随笔 1万+

struts2 学习笔记

今天开始struts2学习,记录自己学习期间遇见问题以及自身感受过程。(*^__^*) …… 弄个简单struts2 sample启动服务相关的Exception 导入如下5个jar freemarker-x.x.x.jar; ognl-x.x.x.jar; struts2-core-x.x.x.jar; xwork-core-x.x.x.jar; commo...

u010372462的博客 82

【struts】struts初始化主线

struts2 三条主线之一:初始化主线

厚积薄发者,轻舟万重山 1152

Struts2常见异常 Dispatcher initialization failed filter initialization failed

Dispatcher initialization failed。。等错误 解决方案  一般导入七个包就行了 http://blog.csdn.net/helifengwell/article/details/5855144 一般在struts 2.2.1  上面的就能够解决了。但是我的struts 是struts 2.2.3。会要导入九个包。 多出来的分别是: commons-

lilang66的专栏 1405

struts2错误:The Struts dispatcher cannot be found.

The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, wh

Jelly 571

struts2 在服务器上部署出现的 Dispatcher initialization failed

有时候使用struts2基本的5个核心包外 出现如下错误可能需要导入其他包: 用的是struts2.2.1 加入包错误提示为 信息: Parsing configuration file [struts.xml] 2010-8-25 15:49:29 com.opensymphony.xwork2.util.logging.commons.CommonsLogger er

KJ345002013的专栏 704
上一篇: Struts2执行流程源码解析
下一篇: struts2拦截器源码阅读笔记
NoExceptionSir
博客等级 码龄10年 11粉丝 39原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值