Strust Components-actionservlet Detailed

Source: Internet
Author: User
Tags system log

As we all know, the Struts controller component is responsible for accepting user requests, for more models, and for returning the appropriate view components to the user.
The controller separates the model layer from the view layer so that different views can be developed for the same model.
The three main components of struts at the bottom
Actionservlet component: A central controller that acts as a struts framework
Requestprocessor Component: Request processor acting as each child application module
Action component: Real to deal with a specific business.

I. The init () method of struts
Only one instance of Actionservlet exists in the struts application, and the servlet container loads the Actionservlet class at startup or when the user first requests actionservlet. In both cases, The servlet container executes its init () method immediately after the Actionservlet container is loaded, which guarantees that Actionservlet has been initialized to process user requests.

The initialization process for struts is described below, based on Init ()
Code public void init ()  throws servletexception {               // wraps the entire initialization in a  try/catch to better handle            //  unexpected exceptions and errors to provide better feedback             // to the developer             try {  //calls the Initinternal () method to initialize the message resources within the Struts framework. such as notifications, warnings, and error messages related to the system log.    1) initinternal ();      //Calling the Ininother () method to load Actionservlet initialization parameters, such as config parameter    2, from Web.xml file Initother ();      //Call Initservlet () method, Loads the Actionservlet URL mapping information from the Web.xml file. Also registers the DTD files used by the Web.xml file and the Struts profile, which authenticate the syntax of the web.xml and struts configuration files. One of the methods The  digester class is responsible for parsing web.xml,Initializes the string Servletmapping property    3)  initservlet ();      //Put the Actionservlet instance in ServletContext    Getservletcontext (). setattribute ( Globals.action_servlet_key, this);      //initialization of a factory for the creation of Moduleconfig    initmoduleconfigfactory ();      //, load and resolve default struts profile/web-inf/struts-config.xml, create moudleconfig instances, and place them in ServletContext    4) Moduleconfig moduleconfig = initmoduleconfig ("",  config);      //loading and initializing the message resource for the default child application module, messageresources the object and storing it in the ServletContext.    5) initmodulemessageresources (moduleconfig);      //loading and initializing the data source for the default child application module, ignoring this process if no <data-sources > element is defined in the struts configuration file.    6) initmoduledatasources (moduleconfig);      //loading and initializing all plugins for default child application    7) initmoduleplugins (moduleconfig);      //Frozen Moduleconfig (cannot be modified before the method returns, otherwise an exception will be thrown)    Moduleconfig.freeZe ();               //If there are other child application modules, repeat the 4-7 step          enumeration names = getservletconfig (). Getinitparameternames ();                while  ( Names.hasmoreelements ())  {                    String name =  (String)  names.nextelement ();                    if   (!name.startswith ("config/"))  {                        continue;                    }           &nbsP;        string prefix = name.substring (6);                     Moduleconfig = initmoduleconfig                          (Prefix, getservletconfig (). Getinitparameter (name));                     Initmodulemessageresources (moduleconfig);                     Initmoduledatasources (moduleconfig);                     Initmoduleplugins (moduleconfig);                     ModuleconfIg.freeze ();        &nbsp}      //Save each child module application (except the default) prefix to a character array. and placed in the ServletContext    this.initmoduleprefixes (This.getservletcontext ());   /Release The created Digester instance for reading the configuration file, freeing memory                 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. ", &NBSP;T);                throw new  Unavailableexception (T.getmessage ());            }       }  

To save each child module application (except the default) prefix to a character array and place it in ServletContext, for the default child application module, the key for storing his moudleconfig instance in the Appclication range is " Org.apache.struts.action.MODULE ", other modules such as/account, stored key for Org.apache.struts.action.module/account, message, The ServletContext key exists in the data source and plug-in, and is similar to the above method, not explained.

Two. Actionservlet method of Process
When Actionservlet receives an HTTP request, the process () method is invoked in the doget () or Dopost () method to process the request.
Code public void Doget (HttpServletRequest request, httpservletresponse response) throws Ioexcep       tion, servletexception {process (request, response); }
Code public void DoPost (HttpServletRequest request, httpservletresponse response) throws IO       Exception, Servletexception {process (request, response); }
Here's the process method, which doesn't look complicated, but the other methods he calls are more complex.
Code   protected void process (httpservletrequest request, httpservletresponse  Response)            throws IOException,  servletexception {           // According to the information in the request, find the corresponding sub module from the ServletContext moduleconfig, and the messageresources below it, and put it in the request, Make other components easy for the request to obtain application configuration information and message resources.            moduleutils.getinstance (). Selectmodule (Request,  getservletcontext ());   //Remove Moudleconfig instance config            moduleconfig  config = getmoduleconfig (Request);        //The Requestprocessor instance of this module from ServletContext, according to the information of this sub module in config             RequestProcessor processor =  Getprocessorformodule (config);        //If ProcesSor the instance is empty, create a new one. and put it in the ServletContext.            if  (processor == null)  {               processor =  Getrequestprocessor (config);           &nbsp}   //Call Requestprocessor Process method processing,            processor.process (Request, response);        }  

Three. Extended Actionservlet class
starting with Struts1.1, most features have been moved to the Requestprocessor class to mitigate the burden of actionservlet, so there is no need to extend the Actionservlet class

If you need to create your own actionservlet, you can create a subclass of it. Overrides the Init () method (or other method), can write some of its own operations, but first call Super.init ();
Define the following classes:
Code package sample;                    public class Extendedactionservlet extends Actionservlet {public void init () throws Servletexception {                    Super.init ();     Do some operations .........} }
After you extend the class, you should also configure the following in the Web.xml file:
Code <servlet> <servlet-name>sample</servlet-name> <servlet-class>sample. extendedactionservlet</servlet-class> </servlet> <servlet-mapping> <servlet-n Ame>sample</servlet-name> <url-pattern>/action/*<url-pattern>
The/action/* above represents the responsibility for handling all URLs prefixed with/action, followed by/representing the escape

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.