Struts1.1b3 partial source code analysis

xiaoxiao2021-03-06  109

Struts1.1b3 partial source code analysis. Reading 3476 Source CN-Java Original: Lonely Soul

Struts1.1 Source Code Analysis 1: Description This article analyzes Struts1.1b3, mainly description of Struts1.1 work by analyzing the analysis of source code. This article is not suitable for beginners, suitable for programmers based on Struts development. The following description; there will be some clauses such as ActionServlet, RequestProcessor, ModuleConfig. Take the workflow in the way in which the source code is taken. Special declaration: struts1.1 code copyright belongs to Apache Follow the Apache Software License, Version 1.1. This article belongs to the lonely soul of individual, any individual or organization wants to reprint, please contact me. And get my authorization to reprint. (If the author's contact information is not found, the author can contact me Duoshan@hotmail.com) 2: ActionServlet analysis Let's first take a look at the configuration file using the struts.

Actionorg.Apache.struts.Action.ActionServlet Definitions-config / web-inf / tiles-defs.xml, / web-inf / tiles-tests-defs.xml, / web-inf / tiles-tutorial-defs.xml, / WEB-INF / tiles-examples-defs.xml definitions-debug0 definitions-parser-details0 definitions-parser-validatetrue config / WEB-INF / struts-config.xml config / examples / WEB-INF / struts-examples-config.xml config / test / WEB-INF / struts-tests-config.xml config / tutorial / WEB-INF / struts-tutorial-config.xml validatetrue debug2 detail2 applicationorg.apache.struts.webapp.tiles.dev1-1.ApplicationResources 2 action * .do Next, let's take a look at the specific use of the ActionServlet. HTTP request. Servlet is in executing doget (), dopost (), call init () first (), let's first analyze the init () method / *** Initialize this servlet. Most of the processing has been factored Into * Support Methods SO That You Can Override Particular FunctionAl Level. * Servlet Initialization, Note Initialization Sequence * @Exception ServleTexception IF we can not configure ourselves correctly * / public void init () throws ServletException {// Note that the order of the initialization // Initialize our internal MessageResources bundleinitInternal (); // Initialize other global characteristics of the controller servlet // address some global variables as provided : debug, detail, etc. initOther (); // Initialize the servlet mapping under which our controller servlet // is being accessed This will be used in the & html: form> // tag to generate correct destination URLs for form submissions // main. It is a registration DTD file and parse web.xml about the configuration of the ActionServlet.

Such as the hyperfix name .// configure the processing rules That We need // Digester.AddCallMethod ("Web-App / Servlet-MApping", // "AddserveTMApping", 2); // Digester.AddCallParam ("Web-App / Servlet-mapping / servlet-name ", 0); // Digester.addCallParam (" Web-App / Servlet-Mapping / URL-Pattern ", 1); // INITSERVLET () will put Struts default suffix name Eliance from Web.xml is // is also the following configuration in Web.xml: ////Aaction//*.do// The default will be handled by Struts by default, you can modify it yourself // INITSERVLET (); // Initialize Modules As Needed // Save Class Instance GetServletContext () in Attribute (Globals.Action_Servlet_Key, this); // Based on the configuration file to generate moduleconfig, this is a very important step. / / In Tiles, first parse a profile of "Mark 0" in the configuration: /Web-inf/struts-config.xml// Use the initModuleConfig method to parse the XML file. // Parameter is prefix: "", Paths: "/WEB-INF/struts-config.xml"ModuleConfig moduleConfig = initModuleConfig (" ", config); // initialize MessageinitModuleMessageResources (moduleConfig); // initialize JDBC DataSourceinitModuleDataSources (moduleConfig); // initialize PlunIninitModulePlugIns (moduleConfig); moduleConfig. Freeze (); // You can use multiple profiles after Struts1.1, which is the profile of the default configuration file is the // comment as "Mark 0": / Web-INF / ST After ruts-config.xml, parsing other profiles enumeration name = getServletConfig (). getInitParameterNames (); // Eliminate the comment as "Mark 1", "Mark 2", "Mark 3" corresponding configuration file while (Names.hasMoreElements ()) {// File name String name = (String) Names.nexTelement (); if (! Name.startswith ("config /")) {Continue;} // string prefix = name.substring (6); moduleConfig = initModuleConfig (prefix, getServletConfig () getInitParameter (name).); initModuleMessageResources (moduleConfig); initModuleDataSources (moduleConfig); initModulePlugIns (moduleConfig); moduleConfig.freeze ();} destroyConfigDigester ();

} / *** This method uses the Digester parse XML, introduced on the use of the Digester see my other article * Initialize the application configuration information for the * specified module. ** @param prefix Module prefix for this module * @param paths Comma-separated list of context-relative resource path (s) * for this modules's configuration resource (s) ** @exception ServletException if initialization can not be performed * @since Struts 1.1 * / protected ModuleConfig initModuleConfig (String prefix, String paths) throws ServletException {if (log.isDebugEnabled ()) {log.debug ( "Initializing module path '" prefix "' configuration from '" paths "'");} // Parse the configuration for this moduleModuleConfig config = null ; InputStream input = null; String mapping = null; try {// create ModuleConfig factory marking method: prefixModuleConfigFactory factoryObject = ModuleConfigFactory.createFactory (); config = factoryObject.createModuleConfig (prefix); // Support for module-wide ActionMapping type overridemapping = getServletConfig (). getInitParameter ("mapping"); if (mapping! = NUL l) {config.setActionMappingClass (mapping);} // Configure the Digester instance we will use // get XML parsing digesterDigester digester = initConfigDigester (); // Process each specified resource pathwhile (paths.length ()> 0) { // Start the parsing of the file Digester.push (config) of the specified path file name; string path = null; // is multiple and use "," split int COMMA = paths.indexof (','); // exist Multiple profiles IF (COMMA> = 0) {// First resolve the first Path = Paths.SUBSTRING (0, COMMA) .trim (); // Paths Store the remaining file name next to processes Paths = paths. Substring (COMMA 1);} else {// The current only one path = paths.trim (); // There is no remaining, the next loop will exit the point "Point Break" in the unique cycle according to the above sentence. Cycling Paths = ""

} // All parsing completes the jump out cycle // point breakif (path.length () <1) {Break;} // according to the file name URL URL = GetServletContext (). GetResource (path); inputsource is = new input filece (URL) .ToExternalForm ()); Input = getServletContext (). getResourceAsStream (PATH); is.setByTestream (Input); Digester.Parse (IS); // Save the analysis of the moduleconfig instances //, "Mark," 1 "Config / Examples", // key is: "org.apache.struts.Action.moduleexample" // globals.module_key value is: org.apache.struts.Action.ModulegetServletContext (). Setttribute (globals .MODULE_KEY prefix, config); input.close ();}} catch (Throwable t) {log.error (internal.getMessage ( "configParse", paths), t); throw new UnavailableException (internal.getMessage ( "configParse ", Paths);} finally {if (input! = null) {Try {INPUT.CLOSE ();} catch (ooexception e) {;}}} // force creation and registration of dynaactionformclass instances // for all Dynamic Form Beans We Wil Be Using / / Depending on the ModuleConfig instance, the configured FORMBEAN configuration // Note: Because the FORMBEAN's instance is created before the Struts is created before the Action instance is created, you can perform Perform (1.1 before), Execute (1.1) needs to use FormBea Nformbeanconfig fbs [] = config.FindFormBeanconfigs (); for (int i = 0; i

All POST methods in the Servlet protocol will call the following methods to handle the PUBLIC VOID DOPOST (HTTPSERVLETREQUEST REQUEST, HTTPSERVLETREQUEST REQUEST, HTTPSERVLETREQUEST REQUEST, HTTPSERVLETREQUEST Request, "HTTPSERVLETREQUEST REQUEST, HTTPSERVLETREQUEST REQUEST, HTTPSERVLETREQUEST Request," The servleTexception {} get method also calls a similar method to handle the POST, GET method call the same Method Process (Request, Response); to handle specific requests as follows: / *** Each submitted action * Perform The Standard Request Processing for this request, and create * the corresponding response. ** @Param Request The servlet request we are processing * @param response The servlet response we are creating ** @exception IOException if an input / output error occurs * @exception ServletException if a servlet exception is thrown * / protected void process (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {// set or remove AttributeRequestUtils.selectModule (request, getServletContext ()); // specific treatment to RequestProcessor to deal HttpRequest, HttpResponse // this is a very typical design pattern // Here we will detail To analyze the RequestProcessor, it is easy to understand the Struts' running method getRequestProcessor (Request, Response);} 3: RequestProcessor analysis through the previous analysis We know httpreq in Struts UEST, HTTPRESPONSE processing is handed over to the processProcessor's Process () method to process.

Let us look at the process method / *** Process an HttpServletRequest and create the * corresponding HttpServletResponse. ** @param request The servlet request we are processing * @param response The servlet response we are creating ** @exception IOException if an input / output error occurs * @exception ServletException if a processing exception occurs * / public void process (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {// Wrap multipart requests with a special wrapper // If upload, the MultipartRequestWrapper a return () request = processMultipart (request); // Identify the path component we will use to select a mapping // obtained by analyzing request of the submitted form Form actionString path = processPath (request, response); if (path == null) {return } if (log.isinfoenabled ()) {log.info ("Processing a '" "' for Path ' PATH "');} // select a local for the current User IF Requested // Localization ProcessLocale (Request, Response); // Set The Content Type and no-Caching Headers if RequestedPR ocessContent (request, response); // Set Cache is not saved processNoCache (request, response); // General purpose preprocessing hookif {return;} (processPreprocess (request, response)!) // Identify the mapping for this request // give After PATH, according to the configuration of the configuration file (Struts-config.xml), a // actionMApping instance // actionmapping inherited actionconfig // Take a closer look at the codeMApping code can be found: // The following paragraph will be resolved. ActionMApping instance // The ActionServlet actually has created all ActionMApping instances // in initialization. The processMapping method is actually from Attribute to get // to save an instance of ActionMApping, which is understood to save all ActionMapping in Attribute when starting at Tomcat. So when Tomcat is started // is slow, if struts-config.xml has problems starting, it will be wrong.

/ *** Type = "org.apache.tests.Webapp.tiles.test.testactionTITIONAAction"> ** /// **** Note that the order of the creation instance // ActionMApping instance has been created, now from Atribute to take ActionMapping mapping = processMapping (request, response, path); if (mapping == null) {return;} // Check for any role required to perform this actionif {return (processRoles (request, response, mapping)!); } // process any actionform bean related to this request / / Actionform instance is obtained according to mapping. // The same name ActionForm will only create once in the system. Actionform Form = ProcessActionform (Request, Response, Mapping); // Stack ProcessPopulate (Request, Response, Form, MApping); // Processing the verification, calling an actionform's Validate method / / If an error will return to the previous page / / That is to say, you will do check if it is not created, you will do check if (! "} // process a forward or incrus specified by this mappingif (... response, mapping)) {return;} if (processInclude (request, response, mapping))! {return;} // Create or acquire the Action instance to process this request // get next instance obtained after ActionMapping, ActionForm of Action Instance // Instance If you have created from Map If you do not create a Map to save an Action instance, you have implemented action action = processActioncreate (request, response, mapping); if (action == NULL) {RETURN;} // call the action instance itself // In an actionMApping, ActionForm, an Action instance creation // Call an Execute () method to get an actionForward // Because all executable Action must have Override Action EXECUTE () / perform () method Actionforward Forward = ProcessActionPerform (Request, Response, Action, Form, Mapping); // process the return ActionForward Instance // ACTI ON has been executed normally, and will return to another page ProcessctionForward (Request, Response, Forward) after the execution is completed; After creation, you will perform the action of an Execute () method.

Why create an actionmapping, Actionform, Action ?????? 4: ModuleConfig analysis now we must understand ModuleConfig, because too many places are used. In fact, ModuleConfig is an interface has an implementation. Org.apache.struts.config.Impl.ModuleConfigImpl does not have to analyze. Let's take a look at this interface.

package org.apache.struts.config;. / *** The collection of static configuration information that describes a * Struts-based module Multiple modules are identified by * a prefix at the beginning of the context * relative portion of the request URI. If no module prefix can be * matched, the default configuration (with a prefix equal to a zero-length * string) is selected, which is elegantly backwards compatible with the * previous Struts behavior that only supported one module. ** @author Rob Leland * @version $ revision: 1.2 $ $ date: 2002/12/201/2016 has been set, any attempt to modify the configuration will return an * IllegalStateException * / boolean getConfigured ();. / *** The controller configuration object for this module * / ControllerConfig getControllerConfig ();. / *** The controller configuration object For this module. * @Param CC The Controller Configuration Object for th . Is module * / void setControllerConfig (ControllerConfig cc);. / *** The prefix of the context-relative portion of the request URI, used to * select this configuration versus others supported by the controller * servlet A configuration with a prefix of a zero-length String is the * default configuration for this web module * / String getPrefix ();. / *** The prefix of the context-relative portion of the request URI, used to * select this configuration versus others supported by the Controller * servlet. a configuration with a prefix of a zero-length string is the * default configuration for this web module. * / public void setprefix (String prefix);

/ *** The default class name to be used when creating action mapping * instances * / String getActionMappingClass ();.. / *** The default class name to be used when creating action mapping * instances * @param actionMappingClass default class name to be used when creating action mapping * instances * / void setActionMappingClass (String actionMappingClass);. / *** Add a new ActionConfig instance to the set associated * with this module ** @param config The new configuration instance to be added *. * @exception java.lang.IllegalStateException if this module configuration * has been frozen * / void addActionConfig (ActionConfig config); / *** Add a new DataSourceConfig instance to the set associated * with this module ** @param config The new. configuration instance to be added ** @exception java.lang.IllegalStateException if this module configuration * has been frozen * / void addDataSourceConfig (DataSourceConfig config); / *** Add a new ExceptionConfig instance to the set associated * with this module *. * @Param config The new configuration instance to be added ** @exception java.lang.IllegalStateException if this module configuration * has been frozen * / void addExceptionConfig (ExceptionConfig config); / *** Add a new FormBeanConfig instance to the set associated * with this module . ** @param config The new configuration instance to be added ** @exception java.lang.IllegalStateException if this module configuration * has been frozen * / void addFormBeanConfig (FormBeanConfig config); / *** Add a new ForwardConfig instance to the Set of global * forwards associated with this module. ** @Param config the new configuration instance to be added ** @

exception java.lang.IllegalStateException if this module configuration * has been frozen * / void addForwardConfig (ForwardConfig config); / *** Add a new MessageResourcesConfig instance to the set * associated with this module ** @param config The new configuration instance. to be added ** @exception IllegalStateException if this module configuration * has been frozen * / void addMessageResourcesConfig (MessageResourcesConfig config); / *** Add a newly configured {@link org.apache.struts.config.PlugInConfig} instance to the set of * plug-in Actions for this module ** @param plugInConfig The new configuration instance to be added * / void addPlugInConfig (plugInConfig plugInConfig);. / *** return the action configuration for the specified path, if any; * otherwise return . null ** @param path path of the action configuration to return * / ActionConfig findActionConfig (String path); / *** return the action configurations for this module If there are * none, a zero-length array is returned *.. / ActionConfig [] Findactio nConfigs (); / *** Return the data source configuration for the specified key, if any; * otherwise return null ** @param key Key of the data source configuration to return * / DataSourceConfig findDataSourceConfig (String key);. / * . ** Return the data source configurations for this module If there * are none, a zero-length array is returned * / DataSourceConfig [] findDataSourceConfigs ();. / *** Return the exception configuration for the specified type, if any; * OtherWise Return Null. ** @Param Type Exception Class Name To Find A Configuration for * / ExceptionConfig FindexceptionConfig (String Type);

. / *** Return the exception configurations for this module If there * are none, a zero-length array is returned * / ExceptionConfig [] findExceptionConfigs ();. / *** Return the form bean configuration for the specified key, if any; * otherwise return null ** @param name name of the form bean configuration to return * / FormBeanConfig findFormBeanConfig (String name);.. / *** return the form bean configurations for this module If there * are none, a zero . -length array is returned * / FormBeanConfig [] findFormBeanConfigs (); / *** return the forward configuration for the specified key, if any;. * otherwise return null ** @param name name of the forward configuration to return * / ForwardConfig findForwardConfig (String name);. / *** Return the form bean configurations for this module If there * are none, a zero-length array is returned * / ForwardConfig [] findForwardConfigs ();. / *** Return the message Resources configuration for the specified key, * if any; @ @Param Key Key of The Data Source Con figuration to return * / MessageResourcesConfig findMessageResourcesConfig (String key); / *** Return the message resources configurations for this module * If there are none, a zero-length array is returned * / MessageResourcesConfig [] findMessageResourcesConfigs ();.. / * . ** Return the configured plug-in actions for this module If there * are none, a zero-length array is returned * / PlugInConfig [] findPlugInConfigs ();.. / *** Freeze the configuration of this module After this method * returns, any attempt to modify the configuration will return * an IllegalStateException * / void freeze ();. / *** Remove the specified action configuration instance ** @param config ActionConfig instance to be removed ** @.

exception java.lang.IllegalStateException if this module configuration * has been frozen * / void removeActionConfig (ActionConfig config); / *** Remove the specified exception configuration instance ** @param config ActionConfig instance to be removed ** @exception java.. lang.IllegalStateException if this module configuration * has been frozen * / void removeExceptionConfig (ExceptionConfig config);. / *** Remove the specified data source configuration instance ** @param config DataSourceConfig instance to be removed ** @exception java.lang. IllegalStateException if this module configuration * has been frozen * / void removeDataSourceConfig (DataSourceConfig config);. / *** Remove the specified form bean configuration instance ** @param config FormBeanConfig instance to be removed ** @exception java.lang.IllegalStateException if This Module Configuration * Has Been Frozen * / Void RemoveFormBeanconfig (FORMBEANCONFIG); / *** Remove The Specified Forward Configuration Instance. ** @Param Config ForwardConfig i nstance to be removed ** @exception java.lang.IllegalStateException if this module configuration * has been frozen * / void removeForwardConfig (ForwardConfig config);. / *** Remove the specified message resources configuration instance ** @param config MessageResourcesConfig instance to Be removed ** @Exception java.lang.illegalstateException if this module configuration * HAS been Frozen * / void RemoveMessageResourcesconfig (MessageResourcesConfig config);} The comments above are very clear. I will not waste everyone, and I want to see it carefully to see his implementation. In fact, it is mainly treated to HashMap (). Five: ActionMapping Analysis Finally, we must see ActionMapping, because you want to know the role of struts-config.xml this configuration file, you should know that ActionMapping has already said ActionMapping Inherited ActionConfig below is ActionMApping added four Method.

/ *** Find and return the ExceptionConfig instance defining * how exceptions of the specified type should be handled. This is * performed by checking local and then global configurations for the * specified exception's class, and then looking up the superclass chain * (again checking local and then global configurations). If no handler * configuration can be found, return null. ** @param type Exception class for which to find a handler * @since Struts 1.1 * / public ExceptionConfig findException (class type) {} / *** Find and return the ForwardConfig instance defining * how forwarding to the specified logical name should be handled. This is * performed by checking local and then global configurations for the * specified forwarding configuration. If no forwarding configuration * can be found, return null. ** @param name Logical name of the forwarding instance to be returned * / public ActionForward findForward (String name) {} / *** Return the logical names of all locally defined forwards for this * mappin g. if there is no claim forwards, a zero-length array * is returned. * / public string [] Findforwards () {} / *** create (if Necessary) and return an {@link actionforward} That * Corresponds To the input property of this Action. ** @since Struts 1.1b2 * / public ActionForward getInputForward () {} or see the following ActionConfig it his base class public class ActionConfig implements Serializable {/ *** Has configuration of this component been completed? * / protected boolean configured = false; / *** The set of exception handling configurations for this * action, if any, keyed by the Type Property. * / Protected HashMap Exceptions = new hashmap ();

/ *** The set of local forward configurations for this action, if any, * keyed by the name property * / protected HashMap forwards = new HashMap ();. / *** The module configuration with which we are associated * /. protected ModuleConfig moduleConfig = null;. / *** The request-scope or session-scope attribute name under which our * form bean is accessed, if it is different from the form bean's * specified name * / protected String attribute = null; / *** Context-relative path of the web application resource that will process * this request via RequestDispatcher.forward (), instead of instantiating * and calling the Action class specified by "type". * Exactly one of forward, include, or * . type must be specified * / protected String forward = null; / *** Context-relative path of the web application resource that process * this request via RequestDispatcher.include will (), instead of instantiating * and calling the Action class specified by "Type". * exactly one of forward, include, or * type virt be specified. * / prot ected String include = null; / *** Context-relative path of the input form to which control should be * returned if a validation error is encountered Required if "name" * is specified and the input bean returns validation errors * /.. protected String input = null; / *** Fully qualified Java class name of the * MultipartRequestHandler implementation class used to * process multi-part request data for this Action * / protected String multipartClass = null;. / *** name of the form Bean, if any, associated with this action. * / protected string name = NULL DITIN

/ *** General purpose configuration parameter that can be used to pass * extra iunformation to the Action instance selected by this Action * Struts does not itself use this value in any way * / protected String parameter = null;.. / *** Context-relative path of the submitted request, starting with a * slash ( "/") character, and omitting any filename extension if * extension mapping is being used * / protected String path = null;. / *** Prefix used to match request parameter names to form ben property * names, if any * / protected String prefix = null;. / *** Comma-delimited list of security role names allowed to request * this Action * / protected String roles = null;. / * ** Identifier of the Scope ("Request" or "session") WITHIN WHICH * OUR FORM Bean IS Accessed, if any. * / Protected scope = "session"; / *** SUFFIX Used to match request parameter names to form Bean Property * Names, if any. * / protected string suffix = null; / *** Fully Qualified Java Class Name of the Action Class * to be used to process req uests for this mapping if the * forward and include properties are not set * Exactly one of forward, include, or * type must be specified * / protected String type = null;.. / *** Should the validate () method of the Form bean associated * with this action be called? * / protected boolean validate = true;} ActionConfig is a typical valueObject. So other Get / SET methods I will not write. Looking at this code must be tied with Struts-Config.xml. According to Struts-Config.xml, find each configuration file to eventually generate an actionConfig, the correspondence between them. If you want to extend struts, ActionMapping estimates you must modify. There is also an ActionServlet, you have to modify it. Six: Endy language analyzes some of the code to do some outlines.

转载请注明原文地址:https://www.9cbs.com/read-124988.html

New Post(0)