Structs Deep Research (i)-----The working principle and components of the Struts framework

Source: Internet
Author: User
Tags object config exception handling functions html tags implement net root directory

The working principles and components of the Struts framework



For struts to control and process customer requests, let us specify this by introducing the four core components of struts. These are the following components: Actionservlet. Action classes,action Mapping (here includes Actionforward), Actionfrom Bean.



Struts Actionservlet Controller Object



Actionservlet inherits from the Javax.servlet.http.HttpServlet class, and its role in the struts framework is the central controller. It provides a central location to handle all terminal requests. The controller Actionservlet is primarily responsible for assembling the HTTP client request information and forwarding it to the appropriate processor according to the specified description of the configuration file.



According to the Servelt standard, all servlet must be declared in the Web configuration file (web.xml). Similarly, Actoinservlet must be described in the Web application configuration file (Web.xml), and the configuration information is as follows.



<servlet>



<servlet-name>action</servlet-name>



<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>



</servlet>



The full request URI exists in the *.do pattern and is mapped to this servlet, configured as follows:



<servlet-mapping>



<servlet-name>action</servlet-name>



<url-pattern>*.do</url-pattern>



</servlet-mapping>



A request URI for this pattern conforms to the following format:



Http://www.my_site_name.com/mycontext/actionName.do







The central controller provides a centralized access point for all presentation layer requests. The abstract concepts provided by this controller mitigate the difficulties developers have in building public application services, such as managing views, sessions, and form data. It also provides a common mechanism such as error and exception handling, navigation, internationalization, data validation, data conversion, and so on.







When a user submits a request to the server, the information is actually first sent to the controller Actionservlet, and once the controller has obtained the request, it passes the request information to some auxiliary class (help classes) processing. These helper classes know how to handle the business operations that correspond to the request information. In struts, this auxiliary class is org.apache.struts.action.Action. Typically, developers need to inherit the Aciton class to implement their own action instances.



Struts Action Classes



Actionservlet all submitted requests are delegated to the Requestprocessor object by the controller. Requestprocessor uses the Struts-config.xml file to check the request URI to find the action action identifier.



The role of an action class, such as an adapter (adaptor) between the client request action and the business logic process, which functions to separate the request from the business logic. Such a separation allows multiple point-to-point mappings between the client request and the action class. Also, the action class usually provides other accessibility features, such as authentication (authorization), log (logging), and data validation (validation).



Public Actionforward Execute (actionmapping mapping,



Actionform form,



Javax.servlet.ServletRequest request,



Javax.servlet.ServletResponse response)



Throws Java.io.ioexception,javax.servlet.servletexception







The Execute () method is the most commonly used action. (Note that the previous perform method is no longer supported in struts1.1), and there is an execute () method, please refer to Apidoc, not described here.



When Controller receives a request from a customer, when the request is moved to an action instance, if the instance does not exist, the controller is created first and then the Execute () method of the action instance is invoked. The Struts framework creates only one instance for each action class in the application system. Because all users use this instance, you must make sure that your action class is running in a multithreaded environment. The following figure shows how an execute () method is accessed:













The Execute () method of the action instance







Note that the action subclass that the customer inherits from itself must override the Execute () method because the action class returns null by default.



Struts Action Mapping



It describes how a client request is forwarded and processed by the controller, but how does the controller know what kind of information is being forwarded to the action class? This requires some mapping configuration instructions that correspond to the action and request information. In struts, these configuration mapping information is stored in a specific XML file (such as Struts-config.xml).



These configuration information is read into memory when the system is started and is used by the struts framework during run time. In memory, each <action> element corresponds to an instance of the Org.apache.struts.action.ActionMapping class. The following table shows a login configuration map.



<action-mappings>



<action path= "/logonaction"



Type= "Com.test.LogonAction"



Name= "LogonForm"



Scope= "Request"



input= "Logoncheck.jsp"



Validate= "false" >



<forward name= "Welcome" path= "/welcome.jsp"/>



<forward name= "Failure" path= "/logon_failure.jsp"/>



</action>



</action-mappings>











<form-beans>



<form-bean name= "LoginForm"



Type= "Com.test.LoginForm"/>



</form-beans>



The configuration above indicates that the controller delegates the information to com.test.LogonAction processing when the request information can be submitted through/logonaction.do (where the configured controller is mapped to *.do). Invokes the Execute () method of the Logonaction instance. The mapping instance and the corresponding LogonForm bean information are also passed in. Where Name=logonform, the Actionform Bean declared by the Form-bean element used. The statement on Form-bean is shown below.



Using Actionforward Navigation



Element <forward> indicates that when the execute () method of the action instance is completed or the controller can move the response information to the appropriate place according to mapping. As above reality, if the customer landed successfully, call welcome forward, return the success information to the/welcome.jsp page. At the end of your execute () method, you can return to welcome forward using the following instance code. Of course, your welcome forward must be defined in the action element attribute, as stated above.



Return (Mapping.findforward ("Welcome"));







The Actionforward object is the configuration object. These configuration objects have unique identities that allow them to be retrieved according to meaningful names such as "Success", "failure", and so on. The Actionforward object encapsulates the forward URL path and the requested processor is used to identify the target view. The Actionforward object is created from the <forward> element located in Struts-config.xml. Here is an example of a <forward> element in struts, which belongs to the <action> element range.



<action path= "/editcustomerprofile"



Type= "Packagename.editcustomerprofileaction"



Name= "Customerprofileform" scope= "Request" >



<forward name= "Success" path= "/mainmenu.jsp"/>



<forward name= "Failure" path= "/customerservice.jsp"/>



</action>



Execute (...) based on the execution request processor. method, the next view can be in execute (...) When a value is passed that matches the value specified in the <forward> element's Name property. Method is Org.apache.struts.action.ActionMapping.findForward (...) by the developer in a convenient way. Choose. Actionmapping.findforward (...) Method provides a Actionforward object both from its local scope and from the global scope, returning to Requestprocessor to Requestdispatcher.forward (...) or Response.sendredirect (...) Call the next view. When the <forward> element has the redirect= "false" attribute or the redirect property does not exist, Requestdispatcher.forward (...) is executed; when redirect= "true", the Sendredirect (...) is invoked. Method. The following example illustrates the use of the redirect property:



<forward name= "Success" Path= "/catalog.jsp" redirect= "true"/>



If redirect=true, the URL is established as/contextpath/path because Httpservletresponse.sendredirect (...) The URL is interpreted as "/" relative to the servlet container root directory.



If Redirect=false, the URI is established as/path because Servletcontext.getrequestdisptacher (...) Take a virtual directory-related URL.







Here's a little bit about the concept of global-forwards. It describes the Actionforward that the entire application can use in the configuration file, not just a specific action.



<global-forwards>



<forward name= "Logout" path= "/logout.do"/>



<forward name= "error" path= "/error.jsp"/>



</global-forwards>







Struts actionform Bean capture form data



When we explained the Actionservlet,action classes and Action mapping above, we all mentioned the concept of actionform bean. A non-persistent data store for a message transfer (or state transition) of an application system is maintained by the Actionform Bean.



Actionform-derived objects are used to hold the parameters of the request object, so they are in close contact with the user.



A Actionform class was established by Requestprocessor. This occurs when the completed forward to a URL, which maps to the controller servlet instead of the JSP and the corresponding action map specified by the form properties. In this case, if it is not found within the specified range of activities, Requestprocessor will try to find a form bean that might cause a new Actionform object to be created. The Actionform object is found with the <action> element's name attribute within the specified range of activity;



Requestprocessor will then rearrange the form properties and populate the form with the request-time parameters, calling the Form object's validate (...). method to perform server-side user input validation. Validate (...) only when the Validate property in the Actionmapping object is set to true. method is invoked, which is the default behavior. Request.getparametervalues (parametername) is used to get a string[] object, which is used for form fills; The result of the validation should be a Actionerrors object, Use Org.apache.struts.taglib.html.ErrorsTag to display validation errors to the user. Actionform can also be used to save an intermediate model state that is about to be referenced by a view for the current user.



When a form object is found by Requestprocessor, it is passed to the request handler's execute (...) Method. A Actionform object can also be created by the requested processor. The purpose of the Form object is to provide an intermediate model state to use the request scope JSP; This will ensure that the object does not persist after validity expires. By default, all forms are saved as session scope. The existence of a form object out of validity in a session can lead to a waste of memory, and similarly, the request processor must track the lifecycle of the form objects that are saved in the session. A good practice for capturing form data is to have a separate form bean for related tables that span multiple user interactions. The form bean can also be used to store the intermediate model state that can be changed by a custom label when feedback. The label usage in the view avoids combining Java code, so to make a good task partition, the web production group mainly handles the flag, while the application development group mainly handles Java code. The label factor exits the logic of accessing the state of the intermediate model; this logic can be complex when you access nested objects or when enumerating through the aggregation.



Note: In struts1.1, the Actionform check function is gradually stripped out (still available). The validator framework is used for unified management of form data validation for the entire application system. Believe information please refer to: Http://home.earthlink.net/~dwinterfeldt



In the use of actionform, struts advocates the use of Value objects (values object). This will enable customers or developers to have a clearer understanding and use of data state and object state.



For each customer request, the Struts framework generally needs to go through the following steps when dealing with Actionform:



(1) Check the action mapping to determine if the Actionform mapping is already configured in the action



(2) Find the configuration information for the form Bean based on the Name property



(3) Check the scope of the action's Formbean and determine if there is already an instance of this form bean in this range.



(4) If an instance of this form bean already exists in the current range, but is the same type for the current request, reuse it.



(5) Otherwise, rebuild an instance of a form bean



(6) The Reset () method of the form Bean is called



(7) Call the corresponding setter method and assign value to the State property



(8) The Validate () method of the form Bean is invoked if the Validatede property is set to True north.



(9) If the Validate () method does not return any errors, the controller passes the Actionform as a parameter to the Execute () method of the action instance and executes it.







Note: the reset () and validate () methods inherited directly from the Actionfrom class do not implement any processing functions, so it is necessary to overwrite them yourself.



Other components of Struts



The Struts framework itself provides many extensible components or sub frameworks that facilitate developers to build web-tier applications on their architecture. such as upload,collections, logging and so on. Let's take a look at two more important components: the Validationg framework and the struts taglib. For additional components, refer to the Struts User manual (Http://jakarta.apache.org/struts/userGuide).







Validation Framework for Struts



In struts1.1, the validation framework is added. Increased validation of form data submission. Verify that the validate () that was originally required to be in the Actionfrom Bean is validated through the description of the configuration file.



For more information, refer to Http://home.earthlink.net/~dwinterfeldt. Personal suggestion for small application system can be used in this configuration, but for the application system has a large number of web-tier application systems, and business requirements change relatively large, the use of the validation framework may aggravate the difficulty of development, system maintenance. You can draw on the JavaScript Validator Tag of the validation framework.







Struts TagLib



Struts provides a set of extensible custom Tag libraries (TAGLIB) to simplify the process of creating a user interface. Currently includes: Bean tags,html tags,logic tags,nested tags,template Tags these several taglib. For the structure and use of struts taglib, you can refer to the previous introduction about Cutomer Tag Lib, for more information, please refer to



Beanutils



The full name of this component is the bean introspection utilites. Belongs to the Jakarta Commons project team. Primarily to help build JavaBean property Operations (Getter,setter), a property that dynamically defines and accesses a bean is provided. For more information, please refer to.



Http://jakarta.apache.org/commons/beanutils.html



If you are interested in this area, you can refer to some information about Java reflection (Reflectio).



Collections



This component is primarily a collection or List object that has been extended on the basis of the original Java collections framework. For more information, please refer to:



Http://jakarta.apache.org/commons/collections.html and



http://cvs.apache.org/viewcvs/~checkout~/jakarta-commons/collections/STATUS.html?rev=1.13



Digester



This component translates into Chinese meaning "assembler". Its main function is to initialize some Java class objects of the system according to the XML configuration file. Digester helps you specify the mapping model between XML and Java objects, and allows the client to customize the mapping rule (rules). For more information, please refer to



Http://jakarta.apache.org/commons/digester.html












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.