Struts2 两大运行主线:
- 1.初始化主线:初始化主线主要是为Struts2创建运行环境(此处的环境与Struts2身处的Web环境是有区别的),初始化入口StrutsPrepareAndExecuteFilter继承 Filter,遵循Filter规范,初始化只是在应用启动的时候运行一次,以后无论过来多少HttpServletRequest都不会再运行啦。
StrutsPrepareAndExecuteFilter.java
- public void init(FilterConfig filterConfig) throws ServletException {
- InitOperations init = new InitOperations();
- Dispatcher dispatcher = null;
- try {
- FilterHostConfig config = new FilterHostConfig(filterConfig);
- init.initLogging(config);
- dispatcher = init.initDispatcher(config);
-
- init.initStaticContentLoader(config, dispatcher);
-
- prepare = new PrepareOperations(filterConfig.getServletContext(), dispatcher);
-
- execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher);
- this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);
-
- postInit(dispatcher, filterConfig);
- } finally {
- if (dispatcher != null) {
- dispatcher.cleanUpAfterInit();
- }
- init.cleanup();
- }
- }
首先我们来看看,Struts2核心分发器初始化过程:
InitOperations.java
- public Dispatcher initDispatcher( HostConfig filterConfig ) {
- Dispatcher dispatcher = createDispatcher(filterConfig);
- dispatcher.init();
- return dispatcher;
- }
-
-
- private Dispatcher createDispatcher( HostConfig filterConfig ) {
- Map<String, String> params = new HashMap<String, String>();
- for ( Iterator e = filterConfig.getInitParameterNames(); e.hasNext(); ) {
- String name = (String) e.next();
- String value = filterConfig.getInitParameter(name);
- params.put(name, value);
- }
- return new Dispatcher(filterConfig.getServletContext(), params);
- }
顺着流程,接着探索dispatcher.init(),这里是加载配置文件的地方
Dispatcher.java
- public void init() {
-
- if (configurationManager == null) {
- configurationManager = createConfigurationManager(BeanSelectionProvider.DEFAULT_BEAN_NAME);
- }
-
- try {
- init_FileManager();
- init_DefaultProperties();
- init_TraditionalXmlConfigurations();
- init_LegacyStrutsProperties();
- init_CustomConfigurationProviders();
- init_FilterInitParameters() ;
- init_AliasStandardObjects() ;
-
- Container container = init_PreloadConfiguration();
- 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);
- }
- }
让我们截取init_TraditionalXmlConfigurations();的加载过程来了解Struts2是如何来加载我们配置的配置文件的:
- private void init_TraditionalXmlConfigurations() {
-
-
- String configPaths = initParams.get("config");
- if (configPaths == null) {
- configPaths = DEFAULT_CONFIGURATION_PATHS;
- }
- String[] files = configPaths.split("\\s*[,]\\s*");
- for (String file : files) {
- if (file.endsWith(".xml")) {
- if ("xwork.xml".equals(file)) {
- configurationManager.addContainerProvider(createXmlConfigurationProvider(file, false));
- } else {
- configurationManager.addContainerProvider(createStrutsXmlConfigurationProvider(file, false, servletContext));
- }
- } else {
- throw new IllegalArgumentException("Invalid configuration file name");
- }
- }
- }
createStrutsXmlConfigurationProvider方法创建StrutsXmlConfigurationProvider对象,其继承XmlConfigurationProvider对象,而XmlConfigurationProvider 实现了ConfigurationProvider接口,ConfigurationProvider使用java很少见到的多继承机制,继承了ContainerProvider和PackageProvider接口。 XmlConfigurationProvider负责读取和解析配置文件,
- protected PackageConfig addPackage(Element packageElement) throws ConfigurationException {
- String packageName = packageElement.getAttribute("name");
- PackageConfig packageConfig = configuration.getPackageConfig(packageName);
- if (packageConfig != null) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Package [#0] already loaded, skipping re-loading it and using existing PackageConfig [#1]", packageName, packageConfig);
- }
- return packageConfig;
- }
- PackageConfig.Builder newPackage = buildPackageContext(packageElement);
- if (newPackage.isNeedsRefresh()) {
- return newPackage.build();
- }
- if (LOG.isDebugEnabled()) {
- LOG.debug("Loaded " + newPackage);
- }
-
- addResultTypes(newPackage, packageElement);
-
- loadInterceptors(newPackage, packageElement);
-
- loadDefaultInterceptorRef(newPackage, packageElement);
-
- loadDefaultClassRef(newPackage, packageElement);
-
- loadGlobalResults(newPackage, packageElement);
-
- loadGobalExceptionMappings(newPackage, packageElement);
-
- NodeList actionList = packageElement.getElementsByTagName("action");
- for (int i = 0; i < actionList.getLength(); i++) {
- Element actionElement = (Element) actionList.item(i);
- addAction(actionElement, newPackage);
- }
-
- loadDefaultActionRef(newPackage, packageElement);
- PackageConfig cfg = newPackage.build();
- configuration.addPackageConfig(cfg.getName(), cfg);
- return cfg;
- }
其中
- addAction()方法负责读取节点,并将数据保存在ActionConfig中;
- addResultTypes()方法负责读取节点,并将数据保存在ResultTypeConfig中;ResultTypeConfig使用了构造器模式创建对象
- loadInterceptors()方法负责读取节点,并将数据保存在InterceptorConfig中;
- loadInterceptorStack()方法负责读取节点,并将数据保存在InterceptorStackConfig中;
- loadInterceptorStacks()方法负责读取节点,并将数据保存在InterceptorStackConfig中;
而以上这些方法都将会被addPackage()invoke,并将数据汇集到PackageConfig中。
配置文件实际的加载流程: DefaultConfiguration.reloadContainer()时调用了containerProvider.init(this);
XmlConfigurationProvider.java
- public void init(Configuration configuration) {
- this.configuration = configuration;
- this.includedFileNames = configuration.getLoadedFileNames();
- loadDocuments(configFileName);
- }
加载Documents:
- private void loadDocuments(String configFileName) {
- try {
- loadedFileUrls.clear();
- documents = loadConfigurationFiles(configFileName, null);
- } catch (ConfigurationException e) {
- throw e;
- } catch (Exception e) {
- throw new ConfigurationException("Error loading configuration file " + configFileName, e);
- }
- }
-
-
- private List<Document> loadConfigurationFiles(String fileName, Element includeElement) {
- List<Document> docs = new ArrayList<Document>();
- List<Document> finalDocs = new ArrayList<Document>();
- if (!includedFileNames.contains(fileName)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Loading action configurations from: " + fileName);
- }
-
- includedFileNames.add(fileName);
-
- Iterator<URL> urls = null;
- InputStream is = null;
-
- IOException ioException = null;
- try {
- urls = getConfigurationUrls(fileName);
- } catch (IOException ex) {
- ioException = ex;
- }
-
- if (urls == null || !urls.hasNext()) {
- if (errorIfMissing) {
- throw new ConfigurationException("Could not open files of the name " + fileName, ioException);
- } else {
- if (LOG.isInfoEnabled()) {
- LOG.info("Unable to locate configuration files of the name "
- + fileName + ", skipping");
- }
- return docs;
- }
- }
-
- URL url = null;
- while (urls.hasNext()) {
- try {
- url = urls.next();
- is = fileManager.loadFile(url);
-
- InputSource in = new InputSource(is);
-
- in.setSystemId(url.toString());
-
- docs.add(DomHelper.parse(in, dtdMappings));
- } catch (XWorkException e) {
- if (includeElement != null) {
- throw new ConfigurationException("Unable to load " + url, e, includeElement);
- } else {
- throw new ConfigurationException("Unable to load " + url, e);
- }
- } catch (Exception e) {
- throw new ConfigurationException("Caught exception while loading file " + fileName, e, includeElement);
- } finally {
- if (is != null) {
- try {
- is.close();
- } catch (IOException e) {
- LOG.error("Unable to close input stream", e);
- }
- }
- }
- }
-
-
- Collections.sort(docs, new Comparator<Document>() {
- public int compare(Document doc1, Document doc2) {
- return XmlHelper.getLoadOrder(doc1).compareTo(XmlHelper.getLoadOrder(doc2));
- }
- });
-
- for (Document doc : docs) {
- Element rootElement = doc.getDocumentElement();
- NodeList children = rootElement.getChildNodes();
- int childSize = children.getLength();
-
- for (int i = 0; i < childSize; i++) {
- Node childNode = children.item(i);
-
- if (childNode instanceof Element) {
- Element child = (Element) childNode;
-
- final String nodeName = child.getNodeName();
-
-
- if ("include".equals(nodeName)) {
- String includeFileName = child.getAttribute("file");
- if (includeFileName.indexOf('*') != -1) {
-
- ClassPathFinder wildcardFinder = new ClassPathFinder();
- wildcardFinder.setPattern(includeFileName);
- Vector<String> wildcardMatches = wildcardFinder.findMatches();
- for (String match : wildcardMatches) {
- finalDocs.addAll(loadConfigurationFiles(match, child));
- }
- } else {
- finalDocs.addAll(loadConfigurationFiles(includeFileName, child));
- }
- }
- }
- }
- finalDocs.add(doc);
- loadedFileUrls.add(url.toString());
- }
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Loaded action configuration from: " + fileName);
- }
- }
- return finalDocs;
- }
init_CustomConfigurationProviders(); // [5]初始化自定义的provider配置类全名和实现ConfigurationProvider接口,用逗号隔开即可
- private void init_CustomConfigurationProviders() {
- String configProvs = initParams.get("configProviders");
- if (configProvs != null) {
- String[] classes = configProvs.split("\\s*[,]\\s*");
- for (String cname : classes) {
- try {
- Class cls = ClassLoaderUtil.loadClass(cname, this.getClass());
- ConfigurationProvider prov = (ConfigurationProvider)cls.newInstance();
- configurationManager.addContainerProvider(prov);
- } catch (InstantiationException e) {
- throw new ConfigurationException("Unable to instantiate provider: "+cname, e);
- } catch (IllegalAccessException e) {
- throw new ConfigurationException("Unable to access provider: "+cname, e);
- } catch (ClassNotFoundException e) {
- throw new ConfigurationException("Unable to locate provider class: "+cname, e);
- }
- }
- }
- }
接下来我们把目光放到Container container = init_PreloadConfiguration();
上,从代码的表面意义上可以看出是对容器进行初始化
- private Container init_PreloadConfiguration() {
- Configuration config = configurationManager.getConfiguration();
- Container container = config.getContainer();
-
- boolean reloadi18n = Boolean.valueOf(container.getInstance(String.class, StrutsConstants.STRUTS_I18N_RELOAD));
- LocalizedTextUtil.setReloadBundles(reloadi18n);
-
- ContainerHolder.store(container);
-
- return container;
- }
Configuration与ConfigurationManager作为Struts2初始化过程中的两大强力的辅助类,对于配置元素的管理启动了至关重要的作用。
Configuration,提供了框架所有配置元素访问的接口,而且对所有配置元素进行初始化调度,接下来我们就从 Configuration config = configurationManager.getConfiguration();
一点一点地来揭示Configuration对配置元素初始化调度的本质。
- public synchronized Configuration getConfiguration() {
- if (configuration == null) {
- setConfiguration(createConfiguration(defaultFrameworkBeanName));
- try {
- configuration.reloadContainer(getContainerProviders());
- } catch (ConfigurationException e) {
- setConfiguration(null);
- throw new ConfigurationException("Unable to load configuration.", e);
- }
- } else {
- conditionalReload();
- }
-
- return configuration;
- }
关键在于configuration.reloadContainer(getContainerProviders());
方法,我们接着看代码:
- public synchronized List<PackageProvider> reloadContainer(List<ContainerProvider> providers) throws ConfigurationException {
- packageContexts.clear();
- loadedFileNames.clear();
- List<PackageProvider> packageProviders = new ArrayList<PackageProvider>();
-
- ContainerProperties props = new ContainerProperties();
- ContainerBuilder builder = new ContainerBuilder();
- Container bootstrap = createBootstrapContainer(providers);
- for (final ContainerProvider containerProvider : providers)
- {
- bootstrap.inject(containerProvider);
- containerProvider.init(this);
- containerProvider.register(builder, props);
- }
- props.setConstants(builder);
-
- builder.factory(Configuration.class, new Factory<Configuration>() {
- public Configuration create(Context context) throws Exception {
- return DefaultConfiguration.this;
- }
- });
-
- ActionContext oldContext = ActionContext.getContext();
- try {
-
-
- setContext(bootstrap);
- container = builder.create(false);
- setContext(container);
- objectFactory = container.getInstance(ObjectFactory.class);
-
-
- for (final ContainerProvider containerProvider : providers)
- {
- if (containerProvider instanceof PackageProvider) {
- container.inject(containerProvider);
- ((PackageProvider)containerProvider).loadPackages();
- packageProviders.add((PackageProvider)containerProvider);
- }
- }
-
-
- Set<String> packageProviderNames = container.getInstanceNames(PackageProvider.class);
- for (String name : packageProviderNames) {
- PackageProvider provider = container.getInstance(PackageProvider.class, name);
- provider.init(this);
- provider.loadPackages();
- packageProviders.add(provider);
- }
-
- rebuildRuntimeConfiguration();
- } finally {
- if (oldContext == null) {
- ActionContext.setContext(null);
- }
- }
- return packageProviders;
- }
很显然我们在这个方法中看到,方法的参数即是一组配置元素的加载器(ConfigurationProvider) Struts2的初始换主线自此全部结束。
*****************************************华丽的分割线***************************************
下面我们再来看看Struts2的第二条主线:
######请求处理主线 我们回到StrutsPrepareAndExecuteFilter来看看,Filter标准中的doFilter()方法:
- public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
-
- HttpServletRequest request = (HttpServletRequest) req;
- HttpServletResponse response = (HttpServletResponse) res;
-
- try {
- prepare.setEncodingAndLocale(request, response);
- prepare.createActionContext(request, response);
- prepare.assignDispatcherToThread();
- if (excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {
- chain.doFilter(request, response);
- } else {
- request = prepare.wrapRequest(request);
- ActionMapping mapping = prepare.findActionMapping(request, response, true);
- if (mapping == null) {
- boolean handled = execute.executeStaticResourceRequest(request, response);
- if (!handled) {
- chain.doFilter(request, response);
- }
- } else {
- execute.executeAction(request, response, mapping);
- }
- }
- } finally {
- prepare.cleanupRequest(request);
- }
- }
prepare.createActionContext(request, response);
:创建上下文ActionContext并初始化其内部线程安全的ThreadLocal对象
- public ActionContext createActionContext(HttpServletRequest request, HttpServletResponse response) {
- ActionContext ctx;
- Integer counter = 1;
- Integer oldCounter = (Integer) request.getAttribute(CLEANUP_RECURSION_COUNTER);
- if (oldCounter != null) {
- counter = oldCounter + 1;
- }
-
- ActionContext oldContext = ActionContext.getContext();
- if (oldContext != null) {
-
- ctx = new ActionContext(new HashMap<String, Object>(oldContext.getContextMap()));
- } else {
- ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();
- stack.getContext().putAll(dispatcher.createContextMap(request, response, null, servletContext));
- ctx = new ActionContext(stack.getContext());
- }
- request.setAttribute(CLEANUP_RECURSION_COUNTER, counter);
- ActionContext.setContext(ctx);
- return ctx;
- }
prepare.assignDispatcherToThread();
:将dispatcher对象绑定到Dispatcher内部线程安全的instance对象中
request = prepare.wrapRequest(request);
:对HttpServletRequest进行封装,传统的Web容器元素的数据是通过HttpServletRequest 的接口实现访问,但是在Struts2中数据的储存位置发生了变化,它们不在适合于web对象绑定在一起,而是以ActionContext的形式存在于当前 的线程中,故传统的访问方式无法访问到Struts2中的数据,因此Struts2针对这种情况作出了对HttpServletRequest装饰的扩展。
PrepareOperations.java
- public HttpServletRequest wrapRequest(HttpServletRequest oldRequest) throws ServletException {
- HttpServletRequest request = oldRequest;
- try {
-
-
- request = dispatcher.wrapRequest(request, servletContext);
- } catch (IOException e) {
- throw new ServletException("Could not wrap servlet request with MultipartRequestWrapper!", e);
- }
- return request;
- }
Dispatcher.java
- public HttpServletRequest wrapRequest(HttpServletRequest request, ServletContext servletContext) throws IOException {
-
- 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;
- }
ActionMapping mapping = prepare.findActionMapping(request, response, true);
ActionMapping是一个普通的java类,但是它将 URL形式的HTTP请求与Struts2中的Action建立起了联系。Struts2在进行Http请求处理时,由ActionMapper的实现类在运行期查找相应的 事件映射关系并生成ActionMapping对象。
- public ActionMapping findActionMapping(HttpServletRequest request, HttpServletResponse response, boolean forceLookup) {
- ActionMapping mapping = (ActionMapping) request.getAttribute(STRUTS_ACTION_MAPPING_KEY);
- if (mapping == null || forceLookup) {
- try {
-
- mapping = dispatcher.getContainer().getInstance(ActionMapper.class).getMapping(request, dispatcher.getConfigurationManager());
- if (mapping != null) {
- request.setAttribute(STRUTS_ACTION_MAPPING_KEY, mapping);
- }
- } catch (Exception ex) {
- dispatcher.sendError(request, response, servletContext, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);
- }
- }
-
- return mapping;
- }
ActionMapper类具有多个默认的实现类,每个实现类具有不同的ActionMapping查找规则,所以这个地方给我们留下了无限的遐想,是个很好的扩展点。
execute.executeAction(request, response, mapping);
:开始真正执行业务逻辑 ExecuteOperations.java
- public void executeAction(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws ServletException {
- dispatcher.serviceAction(request, response, servletContext, mapping);
- }
Dispatcher.java
- public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,
- ActionMapping mapping) throws ServletException {
-
- Map<String, Object> extraContext = createContextMap(request, response, mapping, context);
-
-
- ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);
- boolean nullStack = stack == null;
- if (nullStack) {
- ActionContext ctx = ActionContext.getContext();
- if (ctx != null) {
- stack = ctx.getValueStack();
- }
- }
- if (stack != null) {
- extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.createValueStack(stack));
- }
-
- String timerKey = "Handling request from Dispatcher";
- try {
- UtilTimerStack.push(timerKey);
- 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 (mapping.getResult() != null) {
- Result result = mapping.getResult();
- result.execute(proxy.getInvocation());
- } else {
- proxy.execute();
- }
-
-
- if (!nullStack) {
- request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);
- }
- } catch (ConfigurationException e) {
-
- 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);
- }
- }
Map<String, Object> extraContext = createContextMap(request, response, mapping, context);
: 该方法主要把Application、Session、Request的key value值拷贝到Map中,并放在HashMap<String,Object>中
Dispatcher.java
- public Map<String,Object> createContextMap(HttpServletRequest request, HttpServletResponse response,
- ActionMapping mapping, ServletContext context) {
-
-
- Map requestMap = new RequestMap(request);
-
-
- Map params = new HashMap(request.getParameterMap());
-
-
- Map session = new SessionMap(request);
-
-
- 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;
- }
接下来调用Configuration对象的reloadContainer()利用ContainerBuilder对象生成Container对象,为生成ActionProxy对象做好准备,
ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy( namespace, name, method, extraContext, true, false);
创建ActionProxyFacotry的过程也完成了ActionInvocation对象的创建:
DefaultActionProxyFactory.java----------createActionProxy()
- public ActionProxy createActionProxy(ActionInvocation inv, String namespace, String actionName, String methodName, boolean executeResult, boolean cleanupContext) {
- DefaultActionProxy proxy = new DefaultActionProxy(inv, namespace, actionName, methodName, executeResult, cleanupContext);
- container.inject(proxy);
- proxy.prepare();
- return proxy;
- }
DefaultActionProxy.java----------prepare()
- protected void prepare() {
- String profileKey = "create DefaultActionProxy: ";
- try {
- UtilTimerStack.push(profileKey);
- config = configuration.getRuntimeConfiguration().getActionConfig(namespace, actionName);
-
- if (config == null && unknownHandlerManager.hasUnknownHandlers()) {
- config = unknownHandlerManager.handleUnknownAction(namespace, actionName);
- }
- if (config == null) {
- throw new ConfigurationException(getErrorMessage());
- }
-
- resolveMethod();
-
- if (!config.isAllowedMethod(method)) {
- throw new ConfigurationException("Invalid method: " + method + " for action " + actionName);
- }
-
- invocation.init(this);
-
- } finally {
- UtilTimerStack.pop(profileKey);
- }
- }
DefaultActionInvocation.java-------------init(ActionProxy proxy)
- public void init(ActionProxy proxy) {
- this.proxy = proxy;
- Map<String, Object> contextMap = createContextMap();
-
-
-
- ActionContext actionContext = ActionContext.getContext();
-
- if (actionContext != null) {
- actionContext.setActionInvocation(this);
- }
-
- createAction(contextMap);
-
- if (pushAction) {
- stack.push(action);
- contextMap.put("action", action);
- }
-
- invocationContext = new ActionContext(contextMap);
- invocationContext.setName(proxy.getActionName());
-
-
- List<InterceptorMapping> interceptorList = new ArrayList<InterceptorMapping>(proxy.getConfig().getInterceptors());
- interceptors = interceptorList.iterator();
- }
DefaultActionInvocation.java---createAction(contextMap);
- protected void createAction(Map<String, Object> contextMap) {
-
- String timerKey = "actionCreate: " + proxy.getActionName();
- try {
- UtilTimerStack.push(timerKey);
- action = objectFactory.buildAction(proxy.getActionName(), proxy.getNamespace(), proxy.getConfig(), contextMap);
- } catch (InstantiationException e) {
- throw new XWorkException("Unable to intantiate Action!", e, proxy.getConfig());
- } catch (IllegalAccessException e) {
- throw new XWorkException("Illegal access to constructor, is it public?", e, proxy.getConfig());
- } catch (Exception e) {
- String gripe;
-
- if (proxy == null) {
- gripe = "Whoa! No ActionProxy instance found in current ActionInvocation. This is bad ... very bad";
- } else if (proxy.getConfig() == null) {
- gripe = "Sheesh. Where'd that ActionProxy get to? I can't find it in the current ActionInvocation!?";
- } else if (proxy.getConfig().getClassName() == null) {
- gripe = "No Action defined for '" + proxy.getActionName() + "' in namespace '" + proxy.getNamespace() + "'";
- } else {
- gripe = "Unable to instantiate Action, " + proxy.getConfig().getClassName() + ", defined for '" + proxy.getActionName() + "' in namespace '" + proxy.getNamespace() + "'";
- }
-
- gripe += (((" -- " + e.getMessage()) != null) ? e.getMessage() : " [no message in exception]");
- throw new XWorkException(gripe, e, proxy.getConfig());
- } finally {
- UtilTimerStack.pop(timerKey);
- }
-
- if (actionEventListener != null) {
- action = actionEventListener.prepare(action, stack);
- }
- }
-
继续回到Dispatcher中的proxy.execute();
继续执行业务逻辑 DefaultActionProxy.java-------------execute()
- public String execute() throws Exception {
- ActionContext nestedContext = ActionContext.getContext();
- ActionContext.setContext(invocation.getInvocationContext());
-
- String retCode = null;
-
- String profileKey = "execute: ";
- try {
- UtilTimerStack.push(profileKey);
-
- retCode = invocation.invoke();
- } finally {
- if (cleanupContext) {
- ActionContext.setContext(nestedContext);
- }
- UtilTimerStack.pop(profileKey);
- }
-
- return retCode;
- }
DefaultActionInvocation.java---invoke()
- public String invoke() throws Exception {
- String profileKey = "invoke: ";
- try {
- UtilTimerStack.push(profileKey);
-
- if (executed) {
- throw new IllegalStateException("Action has already executed");
- }
-
- if (interceptors.hasNext()) {
- final InterceptorMapping interceptor = interceptors.next();
- String interceptorMsg = "interceptor: " + interceptor.getName();
- UtilTimerStack.push(interceptorMsg);
- try {
- resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);
- }
- finally {
- UtilTimerStack.pop(interceptorMsg);
- }
- } else {
- resultCode = invokeActionOnly();
- }
-
-
-
- if (!executed) {
- if (preResultListeners != null) {
- for (Object preResultListener : preResultListeners) {
- PreResultListener listener = (PreResultListener) preResultListener;
-
- String _profileKey = "preResultListener: ";
- try {
- UtilTimerStack.push(_profileKey);
- listener.beforeResult(this, resultCode);
- }
- finally {
- UtilTimerStack.pop(_profileKey);
- }
- }
- }
-
-
- if (proxy.getExecuteResult()) {
- executeResult();
- }
-
- executed = true;
- }
-
- return resultCode;
- }
- finally {
- UtilTimerStack.pop(profileKey);
- }
- }
resultCode = invokeActionOnly();
:真正调用Action实际逻辑的地方
DefaultActionInvocation.java---invokeActionOnly()
- public String invokeActionOnly() throws Exception {
- return invokeAction(getAction(), proxy.getConfig());
- }
-
- protected String invokeAction(Object action, ActionConfig actionConfig) throws Exception {
- String methodName = proxy.getMethod();
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Executing action method = " + actionConfig.getMethodName());
- }
-
- String timerKey = "invokeAction: " + proxy.getActionName();
- try {
- UtilTimerStack.push(timerKey);
-
- boolean methodCalled = false;
- Object methodResult = null;
- Method method = null;
- try {
- method = getAction().getClass().getMethod(methodName, EMPTY_CLASS_ARRAY);
- } catch (NoSuchMethodException e) {
-
- try {
- String altMethodName = "do" + methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
- method = getAction().getClass().getMethod(altMethodName, EMPTY_CLASS_ARRAY);
- } catch (NoSuchMethodException e1) {
-
- if (unknownHandlerManager.hasUnknownHandlers()) {
- try {
- methodResult = unknownHandlerManager.handleUnknownMethod(action, methodName);
- methodCalled = true;
- } catch (NoSuchMethodException e2) {
-
- throw e;
- }
- } else {
- throw e;
- }
- }
- }
-
- if (!methodCalled) {
- methodResult = method.invoke(action, EMPTY_OBJECT_ARRAY);
- }
-
- return saveResult(actionConfig, methodResult);
- } catch (NoSuchMethodException e) {
- throw new IllegalArgumentException("The " + methodName + "() is not defined in action " + getAction().getClass() + "");
- } catch (InvocationTargetException e) {
-
- Throwable t = e.getTargetException();
-
- if (actionEventListener != null) {
- String result = actionEventListener.handleException(t, getStack());
- if (result != null) {
- return result;
- }
- }
- if (t instanceof Exception) {
- throw (Exception) t;
- } else {
- throw e;
- }
- } finally {
- UtilTimerStack.pop(timerKey);
- }
- }
OK action执行完了,还要根据ResultConfig返回到view,也就是在invoke方法中调用executeResult方法。
- if (proxy.getExecuteResult()) {
- executeResult();
- }
DefaultActionInvocation.java---executeResult()
- private void executeResult() throws Exception {
- result = createResult();
-
- String timerKey = "executeResult: " + getResultCode();
- try {
- UtilTimerStack.push(timerKey);
- if (result != null) {
- result.execute(this);
- } else if (resultCode != null && !Action.NONE.equals(resultCode)) {
- throw new ConfigurationException("No result defined for action " + getAction().getClass().getName()
- + " and result " + getResultCode(), proxy.getConfig());
- } else {
- if (LOG.isDebugEnabled()) {
- LOG.debug("No result returned for action " + getAction().getClass().getName() + " at " + proxy.getConfig().getLocation());
- }
- }
- } finally {
- UtilTimerStack.pop(timerKey);
- }
- }
DefaultActionInvocation.java---createResult()
- public Result createResult() throws Exception {
-
- if (explicitResult != null) {
- Result ret = explicitResult;
- explicitResult = null;
-
- return ret;
- }
- ActionConfig config = proxy.getConfig();
- Map<String, ResultConfig> results = config.getResults();
-
- ResultConfig resultConfig = null;
-
- try {
- resultConfig = results.get(resultCode);
- } catch (NullPointerException e) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Got NPE trying to read result configuration for resultCode [#0]", resultCode);
- }
- }
-
- if (resultConfig == null) {
-
- resultConfig = results.get("*");
- }
-
- if (resultConfig != null) {
- try {
- return objectFactory.buildResult(resultConfig, invocationContext.getContextMap());
- } catch (Exception e) {
- if (LOG.isErrorEnabled()) {
- LOG.error("There was an exception while instantiating the result of type #0", e, resultConfig.getClassName());
- }
- throw new XWorkException(e, resultConfig);
- }
- } else if (resultCode != null && !Action.NONE.equals(resultCode) && unknownHandlerManager.hasUnknownHandlers()) {
- return unknownHandlerManager.handleUnknownResult(invocationContext, proxy.getActionName(), proxy.getConfig(), resultCode);
- }
- return null;
- }
具体result.execute(this);
的实现可以参考一下各类中的具体代码:
时间匆忙,只是对整个执行流程做了代码层面的演示,待后续将详细说明附上 ^.^