个人理解 WebWork 与 Struts2 都是将xml配置文件作为 Controler 跳转的基本依据,WebWork 跳转 Action 前 xml 文件的读取依赖 xwork-1.0.jar,底层由 xwork实现,这部门代码读起来不是很轻松,在此做下记录供后续查阅和项目借鉴。这几段代码对应 下图 WebWork 框架流转图中红框框的地方。
WebWork xml配置文件读取的入口、后续的所有处理都是 Action 调用类 DefaultActionProxy 这句代码:
this.config = ConfigurationManager.getConfiguration().getRuntimeConfiguration().getActionConfig(namespace, actionName);
1 public static synchronized Configuration getConfiguration() { 2 if (configurationInstance == null) { 3 configurationInstance = new DefaultConfiguration(); 4 configurationInstance.reload(); 5 } else { 6 conditionalReload(); 7 } 8 return configurationInstance; 9 }
1 public synchronized void reload() throws ConfigurationException { 2 this.packageContexts.clear(); 3 for (Iterator iterator = ConfigurationManager.getConfigurationProviders().iterator(); iterator.hasNext();) { 4 ConfigurationProvider provider = (ConfigurationProvider) iterator.next(); 5 provider.init(this); 6 } 7 rebuildRuntimeConfiguration(); 8 }
ConfigurationManager的 getConfigurationProviders方法实现如下:
public static List getConfigurationProviders() { synchronized (configurationProviders) { if (configurationProviders.size() == 0) { configurationProviders.add(new XmlConfigurationProvider()); } return configurationProviders; } }
具体代码如下:
1 private void loadConfigurationFile(String fileName, DocumentBuilder db) { 2 if (!includedFileNames.contains(fileName)) { 3 if (LOG.isDebugEnabled()) { 4 LOG.debug("Loading xwork configuration from: " + fileName); 5 } 6 includedFileNames.add(fileName); 7 Document doc = null; 8 InputStream is = null; 9 try { 10 is = getInputStream(fileName); 11 if (is == null) { 12 throw new Exception("Could not open file " + fileName); 13 } 14 doc = db.parse(is); 15 } catch (Exception e) { 16 final String s = "Caught exception while loading file " + fileName; 17 LOG.error(s, e); 18 throw new ConfigurationException(s, e); 19 } finally { 20 if (is != null) { 21 try { 22 is.close(); 23 } catch (IOException e) { 24 LOG.error("Unable to close input stream", e); 25 } 26 } 27 } 28 Element rootElement = doc.getDocumentElement(); 29 NodeList children = rootElement.getChildNodes(); 30 int childSize = children.getLength(); 31 for (int i = 0; i < childSize; i++) { 32 Node childNode = children.item(i); 33 if (childNode instanceof Element) { 34 Element child = (Element) childNode; 35 final String nodeName = child.getNodeName(); 36 if (nodeName.equals("package")) { 37 addPackage(child); 38 } else if (nodeName.equals("include")) { 39 String includeFileName = child.getAttribute("file"); 40 loadConfigurationFile(includeFileName, db); 41 } 42 } 43 } 44 if (LOG.isDebugEnabled()) { 45 LOG.debug("Loaded xwork configuration from: " + fileName); 46 } 47 } 48 }