Struts-three major components (I) actionservlet

Source: Internet
Author: User

The actionservlet class is a built-in core controller component of the Struts framework. It inherits javax. servlet. HTTP. httpservlet class. Struts generally starts from loading actionservlet. Therefore, it plays the role of a central controller in the MVC model and is responsible for receiving user requests and returning them to the user's appropriate view components. the Controller separates the model layer from the view layer so that different views can be developed for the same model.

 

The following are three major components of struts:

Actionservlet component: acts as the central controller of the Struts framework. Only one instance of actionservlet exists in the struts application.

Requestprocessor component: serves as the request processor for each sub-application module.

Action component: to process a specific business ..

 

Actionservlet

The servlet container loads the actionservlet class at startup or when the user requests the actionservlet for the first time. in both cases, the servlet container will execute its Init () method immediately after the actionservlet container is loaded. This ensures that the actionservlet has been initialized when processing user requests.

Java code -- Init ()


 

Public void Init () throws servletexception {final string configprefix = "config/"; Final int configprefixlength = configprefix. length ()-1; try {// call the initinternal () method to initialize Message Resources in the Struts framework, such as notifications, warnings, and error messages related to system logs. initinternal (); // call the ininother () method from the web. load the initialization parameters of the actionservlet in the XML file, such as the config parameter initother (); // call the initservlet () method from the web. the URL ing information of the actionservlet is loaded in the XML file. // The web. the DTD used by the XML file and Struts configuration file. // These DTD files are verified by the user. Certificate web. XML and Struts Configuration File Syntax. the digester class in the method is responsible for parsing the web. XML, // initialize the attributes of the string servletmapping initservlet (); initchain (); // put the actionservlet instance in the servletcontext getservletcontext (). setattribute (globals. action_servlet_key, this); // initialize a factory to create moduleconfiginitmoduleconfigfactory (); // load and resolve the default struts profile/WEB-INF/struts-config.xml while creating a moudleconfig instance, put moduleconfig = initmoduleconfig ("", Co Nfig); // load and initialize the Message Resources of the default sub-application module; Explain the messageresources object and store it in servletcontext. initmodulemessageresources leconfig; // load and initialize all the ins initmoduleplugins (moduleconfig); initmoduleformbeans (moduleconfig); initmoduleforwards (moduleconfig); initmoduleexceptionconfigs (moduleconfig ); initmoduleactions (moduleconfig); // freeze moduleconfig (it cannot be modified before the method is returned, otherwise an exception will be thrown) 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 leconfig; initmoduleplugins leconfig; initmoduleformbeans (moduleconfig); initmoduleforwards (moduleconfig); initmoduleexceptionconfigs leconfig; initmoduleactions leconfig; moduleconfig. freeze ();} // store the prefix of each sub-module (except the default one) to a character array and put it in servletcontext. This. initmoduleprefixes (this. getservletcontext (); // release the created digester instance used to read the configuration file and release the memory. 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 // initializedlog. 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 ());}}

-------------------------------------------------

After the actionservlet receives the HTTP request, the process () method is called in the doget () or dopost () method to process the request.

Java code -- Process ()

 

Protected void process (httpservletrequest request, httpservletresponse response) throws ioexception, servletexception {// find the corresponding sub-module moduleconfig from servletcontext according to the information in the request, // and messageresources under it, and put it in the request so that other components can easily obtain application configuration information and Message Resources for the request. moduleutils. getinstance (). selectmodule (request, getservletcontext (); // retrieve the moudleconfig instance configmoduleconfig Config = getmoduleconfig (request); // according to the information of this sub-module in config, obtain the requestprocessor instance requestprocessor processor = getprocessorformodule (config) of this submodule. // If the processor instance is empty, create a new one. and put it in servletcontext. if (processor = NULL) {processor = getrequestprocessor (config);} // call the process method of requestprocessor for processing, processor. process (request, response );}

Actionservlet. Process () does not seem complicated, but the requestprocessor. Process () method he calls is complicated (this will be introduced in the next blog ).

 

Extended actionservlet class

 

Starting from struts1.1, most of the functions of actionservlet have been moved to the requestprocessor class to reduce the burden on actionservlet, so there is basically no need to extend the actionservlet class.

To create your own actionservlet, you can create a subclass of it. overwrite the init () method (or other methods). You can write your own operations, but you must call super first. init ();

Define the following classes:

package sample;  public classExtendedActionServlet extends ActionServlet {          public void init() throwsServletException {                 super.init();                 //do some operations                 ……………          }  }  


 

After the class is extended, configure the following in the web. xml file:

 

<servlet>         <servlet-name>sample</servlet-name>         <servlet-class>sample.ExtendedActionServlet</servlet-class>  </servlet>    <servlet-mapping>        <servlet-name>sample</servlet-name>        <url-pattern>/action/*<url-pattern>  


 

The above/Action/* indicates to process all URLs prefixed with/action, followed by/indicates escape

 

Summary

When the Web server receives a request, it first loads and initializes the actionservlet. Actionservlet reads the struts-config.xml configuration file and saves the configuration file information to the actionmapping object for later use. In struts, it is mainly used to receive user request information, and then pass the request to the corresponding action object according to the System Configuration Requirements. Actionservlet is not really a working class. What actually works is requestdispatcher and action.

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.