struts1原始碼學習3
阿新 • • 發佈:2018-11-29
public void init() throws ServletException { final String configPrefix = "config/"; final int configPrefixLength = configPrefix.length() - 1; // Wraps the entire initialization in a try/catch to better handle // unexpected exceptions and errors to provide better feedback // to the developer try { initInternal(); initOther(); initServlet(); initChain(); getServletContext().setAttribute(Globals.ACTION_SERVLET_KEY, this); initModuleConfigFactory(); // 初始化模組配置 ModuleConfig moduleConfig = initModuleConfig("", config); initModuleMessageResources(moduleConfig); initModulePlugIns(moduleConfig); initModuleFormBeans(moduleConfig); initModuleForwards(moduleConfig); initModuleExceptionConfigs(moduleConfig); initModuleActions(moduleConfig); moduleConfig.freeze(); Enumeration names = getServletConfig().getInitParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); if (!name.startsWith(configPrefix)) { continue; } String prefix = name.substring(configPrefixLength); moduleConfig = initModuleConfig(prefix, getServletConfig().getInitParameter(name)); initModuleMessageResources(moduleConfig); initModulePlugIns(moduleConfig); initModuleFormBeans(moduleConfig); initModuleForwards(moduleConfig); initModuleExceptionConfigs(moduleConfig); initModuleActions(moduleConfig); moduleConfig.freeze(); } this.initModulePrefixes(this.getServletContext()); this.destroyConfigDigester(); } catch (UnavailableException ex) { throw ex; } catch (Throwable t) { // The follow error message is not retrieved from internal message // resources as they may not have been able to have been // initialized log.error("Unable to initialize Struts ActionServlet due to an " + "unexpected exception or error thrown, so marking the " + "servlet as unavailable. Most likely, this is due to an " + "incorrect or missing library dependency.", t); throw new UnavailableException(t.getMessage()); } }
initModuleConfigFactory方法(初始化模組配置工廠?)
protected void initModuleConfigFactory() { String configFactory = getServletConfig().getInitParameter("configFactory"); if (configFactory != null) { //設定class類名,當ModuleConfigFactory呼叫createFactory時,會拿到當前執行緒的classloader去載入這個類,並且返回一個例項。 ModuleConfigFactory.setFactoryClass(configFactory); } }
初始化模組配置程式碼
ModuleConfig moduleConfig = initModuleConfig("", config);
//config就是struts-config路徑,預設/WEB-INF/struts-config.xml
initModuleConfig程式碼
protected ModuleConfig initModuleConfig(String prefix, String paths) throws ServletException { //在這裡建立了一個ModuleConfigFactory,如果使用者沒有配置configFactory,name這個工廠類是org.apache.struts.config.impl.DefaultModuleConfigFactory ModuleConfigFactory factoryObject = ModuleConfigFactory.createFactory(); //建立一個配置,預設是new ModuleConfigImpl(prefix) ModuleConfig config = factoryObject.createModuleConfig(prefix); //又要解析xml了,其中用到ConfigRuleSet來作為解析規則。也可以自己定義RuleSet來解析 //如果自定義的話,引數名實rulesets,多個RuleSet類名用逗號分隔 //自定義ruleset相關程式碼在initConfigDigester中的addRuleSets中 Digester digester = initConfigDigester(); List urls = splitAndResolvePaths(paths); URL url; for (Iterator i = urls.iterator(); i.hasNext();) { url = (URL) i.next(); digester.push(config); //解析每個url,並且處理解析異常。處理解析異常的時候就用到了internal this.parseModuleConfigFile(digester, url); } getServletContext().setAttribute(Globals.MODULE_KEY + config.getPrefix(), config); return config; }
ConfigRuleSet程式碼
public class ConfigRuleSet extends RuleSetBase {
public void addRuleInstances(Digester digester) {
ClassLoader cl = digester.getClassLoader();
digester.addRule("struts-config/action-mappings",new SetActionMappingClassRule());
//根據ActionMappingFactory的create方法建立物件後,放入digester棧中。
//實際上,在ActionMappingFactory中,createObject方法中,獲取到action的className屬性值,然後根據這個值來生成一個例項,然後放入到digester棧中
//如果使用者在struts-config中的action不配置className或者在action-mappings不配置type的話,Name這個className預設是
//org.apache.struts.action.ActionMapping
digester.addFactoryCreate("struts-config/action-mappings/action",
new ActionMappingFactory(cl));
//將action標籤的屬性值全部寫入到上一步生成的例項中
digester.addSetProperties("struts-config/action-mappings/action");
//action結束時,呼叫ModuleConfig的addActionConfig,引數含義:1、匹配字串 2、方法名 3、方法引數型別
digester.addSetNext("struts-config/action-mappings/action",
"addActionConfig", "org.apache.struts.config.ActionConfig");
//設定引數,可以再action中 <set-property value="" property=""/>這樣設定
digester.addRule("struts-config/action-mappings/action/set-property",
new BaseConfigSetPropertyRule());
//異常
digester.addObjectCreate("struts-config/action-mappings/action/exception",
"org.apache.struts.config.ExceptionConfig", "className");
digester.addSetProperties(
"struts-config/action-mappings/action/exception");
digester.addSetNext("struts-config/action-mappings/action/exception",
"addExceptionConfig", "org.apache.struts.config.ExceptionConfig");
digester.addRule("struts-config/action-mappings/action/exception/set-property",
new BaseConfigSetPropertyRule());
//forward
digester.addFactoryCreate("struts-config/action-mappings/action/forward",
new ActionForwardFactory(cl));
digester.addSetProperties(
"struts-config/action-mappings/action/forward");
digester.addSetNext("struts-config/action-mappings/action/forward",
"addForwardConfig", "org.apache.struts.config.ForwardConfig");
digester.addRule("struts-config/action-mappings/action/forward/set-property",
new BaseConfigSetPropertyRule());
//controller,這個實際就是處理request和response的東西。在ActionServlet.process中,processor.process(request, response);這個<pre name="code" class="java">processor就是controller
digester.addObjectCreate("struts-config/controller", "org.apache.struts.config.ControllerConfig", "className"); digester.addSetProperties("struts-config/controller");
//此處只是呼叫了ModuleConfig的setController,目測這東西只能配置一個
digester.addSetNext("struts-config/controller", "setControllerConfig",
"org.apache.struts.config.ControllerConfig");
digester.addRule("struts-config/controller/set-property",
new BaseConfigSetPropertyRule());
//此處和action-mappings有些類似
digester.addRule("struts-config/form-beans",
new SetActionFormBeanClassRule());
<span style="white-space:pre"> </span>//建立formbean(建立的不是type所指的class物件)。是根據className來建立的。
<pre name="code" class="java">//這個className如果不配置,預設使用org.apache.struts.action.ActionFormBean
digester.addFactoryCreate("struts-config/form-beans/form-bean",
new ActionFormBeanFactory(cl));
digester.addSetProperties("struts-config/form-beans/form-bean");
<pre name="code" class="java">//因為在處理struts-config/form-beans開始標籤時,沒有建立新物件,所以此處仍然是ModuleConfig呼叫addFromBean
<pre name="code" class="java"> digester.addSetNext("struts-config/form-beans/form-bean",
"addFormBeanConfig", "org.apache.struts.config.FormBeanConfig");
//Config新增ActionFormBean物件
digester.addObjectCreate("struts-config/form-beans/form-bean/form-property",
"org.apache.struts.config.FormPropertyConfig", "className");
digester.addSetProperties(
"struts-config/form-beans/form-bean/form-property");
digester.addSetNext("struts-config/form-beans/form-bean/form-property",
"addFormPropertyConfig",
"org.apache.struts.config.FormPropertyConfig");
digester.addRule("struts-config/form-beans/form-bean/form-property/set-property",
new BaseConfigSetPropertyRule());
digester.addRule("struts-config/form-beans/form-bean/set-property",
new BaseConfigSetPropertyRule());<pre name="code" class="java"><span style="white-space:pre"> </span>//異常部分
<span style="white-space:pre"> </span> digester.addObjectCreate("struts-config/global-exceptions/exception",
"org.apache.struts.config.ExceptionConfig", "className");
digester.addSetProperties("struts-config/global-exceptions/exception");
digester.addSetNext("struts-config/global-exceptions/exception",
"addExceptionConfig", "org.apache.struts.config.ExceptionConfig");
digester.addRule("struts-config/global-exceptions/exception/set-property",
new BaseConfigSetPropertyRule());
<span style="white-space:pre"> </span><pre name="code" class="java"> digester.addRule("struts-config/global-forwards",
new SetActionForwardClassRule());
<span style="white-space:pre"> </span>//forward
digester.addFactoryCreate("struts-config/global-forwards/forward",
new GlobalForwardFactory(cl));
digester.addSetProperties("struts-config/global-forwards/forward");
digester.addSetNext("struts-config/global-forwards/forward",
"addForwardConfig", "org.apache.struts.config.ForwardConfig");
digester.addRule("struts-config/global-forwards/forward/set-property",
new BaseConfigSetPropertyRule());
digester.addObjectCreate("struts-config/message-resources",
"org.apache.struts.config.MessageResourcesConfig", "className");
digester.addSetProperties("struts-config/message-resources");
digester.addSetNext("struts-config/message-resources",
"addMessageResourcesConfig",
"org.apache.struts.config.MessageResourcesConfig");
digester.addRule("struts-config/message-resources/set-property",
new BaseConfigSetPropertyRule());
<span> </span>//外掛部分
digester.addObjectCreate("struts-config/plug-in",
"org.apache.struts.config.PlugInConfig");
digester.addSetProperties("struts-config/plug-in");
digester.addSetNext("struts-config/plug-in", "addPlugInConfig",
"org.apache.struts.config.PlugInConfig");
digester.addRule("struts-config/plug-in/set-property",
new PlugInSetPropertyRule());
// PluginConfig does not extend BaseConfig, at least for now.
}
}
//以下是各種rule
final class PlugInSetPropertyRule extends Rule {
public PlugInSetPropertyRule() {
super();
}
public void begin(String namespace, String names, Attributes attributes)
throws Exception {
PlugInConfig plugInConfig = (PlugInConfig) digester.peek();
plugInConfig.addProperty(attributes.getValue("property"),
attributes.getValue("value"));
}
}
final class SetActionFormBeanClassRule extends Rule {
public SetActionFormBeanClassRule() {
super();
}
public void begin(String namespace, String name, Attributes attributes)
throws Exception {
String className = attributes.getValue("type");
if (className != null) {
ModuleConfig mc = (ModuleConfig) digester.peek();
mc.setActionFormBeanClass(className);
}
}
}
final class BaseConfigSetPropertyRule extends SetPropertyRule {
public BaseConfigSetPropertyRule() {
super("property", "value");
}
public void begin(Attributes attributes)
throws Exception {
if (attributes.getIndex("key") == -1) {
super.begin(attributes);
return;
}
if (attributes.getIndex("property") != -1) {
throw new IllegalArgumentException(
"<set-property> accepts only one of 'key' or 'property' attributes.");
}
Object topOfStack = digester.peek();
if (topOfStack instanceof BaseConfig) {
BaseConfig config = (BaseConfig) topOfStack;
config.setProperty(attributes.getValue("key"),
attributes.getValue("value"));
} else {
throw new IllegalArgumentException(
"'key' attribute of <set-property> only applicable to subclasses of BaseConfig; "
+ "object on top of stack is " + topOfStack + " [key: "
+ attributes.getValue("key") + ", value: "
+ attributes.getValue("value") + "]");
}
}
}
final class ActionFormBeanFactory extends AbstractObjectCreationFactory {
private ClassLoader cl;
public ActionFormBeanFactory(ClassLoader cl) {
super();
this.cl = cl;
}
public Object createObject(Attributes attributes) {
// Identify the name of the class to instantiate
String className = attributes.getValue("className");
if (className == null) {
ModuleConfig mc = (ModuleConfig) digester.peek();
className = mc.getActionFormBeanClass();
}
// Instantiate the new object and return it
Object actionFormBean = null;
try {
actionFormBean = RequestUtils.applicationInstance(className, cl);
} catch (Exception e) {
digester.getLogger().error("ActionFormBeanFactory.createObject: ", e);
}
return actionFormBean;
}
}
final class SetActionMappingClassRule extends Rule {
public SetActionMappingClassRule() {
super();
}
public void begin(String namespace, String name, Attributes attributes)
throws Exception {
String className = attributes.getValue("type");
if (className != null) {
ModuleConfig mc = (ModuleConfig) digester.peek();
mc.setActionMappingClass(className);
}
}
}
final class ActionMappingFactory extends AbstractObjectCreationFactory {
private ClassLoader cl;
public ActionMappingFactory(ClassLoader cl) {
super();
this.cl = cl;
}
public Object createObject(Attributes attributes) {
// Identify the name of the class to instantiate
String className = attributes.getValue("className");
if (className == null) {
ModuleConfig mc = (ModuleConfig) digester.peek();
className = mc.getActionMappingClass();
}
// Instantiate the new object and return it
Object actionMapping = null;
try {
actionMapping = RequestUtils.applicationInstance(className, cl);
} catch (Exception e) {
digester.getLogger().error("ActionMappingFactory.createObject: ", e);
}
return actionMapping;
}
}
final class SetActionForwardClassRule extends Rule {
public SetActionForwardClassRule() {
super();
}
public void begin(String namespace, String name, Attributes attributes)
throws Exception {
String className = attributes.getValue("type");
if (className != null) {
ModuleConfig mc = (ModuleConfig) digester.peek();
mc.setActionForwardClass(className);
}
}
}
final class GlobalForwardFactory extends AbstractObjectCreationFactory {
private ClassLoader cl;
public GlobalForwardFactory(ClassLoader cl) {
super();
this.cl = cl;
}
public Object createObject(Attributes attributes) {
// Identify the name of the class to instantiate
String className = attributes.getValue("className");
if (className == null) {
ModuleConfig mc = (ModuleConfig) digester.peek();
className = mc.getActionForwardClass();
}
// Instantiate the new object and return it
Object globalForward = null;
try {
globalForward = RequestUtils.applicationInstance(className, cl);
} catch (Exception e) {
digester.getLogger().error("GlobalForwardFactory.createObject: ", e);
}
return globalForward;
}
}
final class ActionForwardFactory extends AbstractObjectCreationFactory {
private ClassLoader cl;
public ActionForwardFactory(ClassLoader cl) {
super();
this.cl = cl;
}
public Object createObject(Attributes attributes) {
// Identify the name of the class to instantiate
String className = attributes.getValue("className");
if (className == null) {
ModuleConfig mc = (ModuleConfig) digester.peek(1);
className = mc.getActionForwardClass();
}
// Instantiate the new object and return it
Object actionForward = null;
try {
actionForward = RequestUtils.applicationInstance(className, cl);
} catch (Exception e) {
digester.getLogger().error("ActionForwardFactory.createObject: ", e);
}
return actionForward;
}
}
本文出自 “helloworld” 部落格,請務必保留此出處http://lawrence16.blog.51cto.com/1908331/1532323