Struts Architecture and working principle

Source: Internet
Author: User
Tags html tags access database
Struts is an open Source project in the Apache Foundation's Jakarta Project, which employs the MVC pattern to help Java developers develop Web applications using EE. Like other Java architectures, Struts is also object-oriented, with the ability to "separate the display logic and the business logic" of the MVC pattern to its fullest. The core of the Structs framework is a resilient control layer based on standard technologies such as Java servlets,javabeans,resourcebundles and XML, as well as some class libraries of Jakarta Commons. Struts consists of a set of mutually collaborative classes (components), Serlvet, and JSP tag lib. The Web application based on struts architecture conforms to the design standard of JSP Model2, which can be said to be a kind of change of traditional MVC design pattern.
  
Struts has its own controller (Controller), while consolidating other technologies to implement the model and view layers. At the model level, struts can be easily combined with data access technologies such as JDBC/EJB, and other third-party libraries such as hibernate/ibatis, or Object Relational Bridge. In the view layer, struts can work with JSPs, including JSTL and JSF, as well as Velocity templates, XSLT, and other presentation layer technologies.
  
Struts supports every professional WEB application and helps create an extended development environment for your application.
  
   the architecture and working principle of struts
  
MVC, the abbreviation for Model-view-controller, is a common design pattern. MVC weakens the coupling between business logic interfaces and data interfaces, and makes the view layer more variable. The workings of MVC are shown in Figure 1 below:
  
 
  
Figure 1
  
Struts is an implementation of MVC, which uses the servlet and JSP tags (which belong to the Java EE Specification) as part of the implementation. Struts inherits the characteristics of MVC and makes corresponding changes and extensions according to the characteristics of Java EE. The architecture and working principle of struts are shown in Figure 2 below:
  
 
  
Figure 2
  
As we can see from Figure 2, the architecture of struts includes three parts, model, view, and Controller (Controller).
  
Let's look at the architecture of struts (Model 2) and how it works from an MVC perspective:
  
1) models (model)
  
In the architecture of struts, the model is divided into two parts: the internal state of the system and the operation that can change the state (transaction logic). The internal state is usually represented by a set of actinform beans. Depending on the design or application complexity, these beans can be self-contained and have a persistent state, or obtain data only when needed (from a database). Large applications typically encapsulate transaction logic (operations) within a method, which can be invoked by a bean that owns state information. A shopping cart bean, for example, has information about the user's purchase of the product, and possibly a checkout () method to check the user's credit card and send a shipping order to the warehouse. In a small program, operations may be embedded in the action class, which is part of the controller role in the Struts framework. This approach works well when logic is simple. It is recommended that the user separate the transaction logic (what to do) from the role that the Action class plays (deciding what to do).
  
2) Views (view)
  
The view is built primarily by JSP, and struts contains the extended Custom tag library (TAGLIB), which simplifies the process of creating a fully internationalized user interface. The current tag library includes: Bean tags, HTML tags, Logic tags, Nested tags and template tags and so on.
  
3) Controller (Controller)
  
In struts, the basic controller component is the instance Servelt in the Actionservlet class, and the actual servlet used in the configuration file is defined by a set of mappings (described by the Actionmapping Class). The operation of the business logic is mainly coordinated by the actions, actionmapping, and Actionforward components, in which the action acts as the real implementation of the business logic, Actionmapping and Actionforward specify the direction in which different business logic or processes are run. Struts-config.xml file Configuration controller.
  
Components in the Struts architecture
  

  
Figure 3
  
Figure 3 above shows the simplest relationship between Actionservlet (Controller), Actionform (form State), and Action (Model wrapper).
The components used in the architecture are the following tables:
Actionservlet Controller
Actionclass contains transaction logic
Actionform Display Module data
Actionmapping Help controller maps requests to operations
Actionforward object used to indicate an action transfer
Actionerror used to store and recycle errors
Struts tag libraries can mitigate the work of development display levels
  
   struts configuration file: Struts-config.xml
  
Struts configuration file Struts-config.xml, we can find this file by default in the directory Web-infstruts-config.xml. The configuration of the file includes four parts, global forwarding, actionmapping class, Actionform bean, and JDBC data source.
  
1) Configure global forwarding
  
Global forwarding is used to create a logical name mapping between JSP pages. Forwarding can be obtained by an instance of the call action mapping, for example: Nuw=mactionmappinginstace.findforward ("LogicalName");
  
Examples of global forwarding:
<global-forwards>
<forward name= "bookcreated" path= "/bookview.jsp"
</global-forwards>
  
Attribute description
Name Global forwarding Names
Path relative to destination URL
  
2) Configure Actionmapping
The Actionmapping object helps with process control within the framework, which maps the request URI to the action class and associate the action class with the Actionform bean. Actionservlet uses these mappings internally and transfers control to instances of specific action classes. All action classes use the Perform () method to implement specific application code, returning a Actionforward object that includes the target resource name in response to forwarding. For example:
  
<action-mappings>
<action path= "/createbook" type= "bookaction" name= "Bookform" scope= "Request" input= "/createbook.jsp"
</action>
<forward name= "Failure" path= "/createbook.jsp"
<forward name= "Cancel" path= "/index.jsp"/>
</action-mappings>
  
Attribute description
The relative path of the path action class
Name of the action bean that the name is associated with this operation
Type is the full name of the action class that is connected to this mapping (with the package name)
Scope Actionform Bean's scope (request or session)
Prefix used to match the prefix of the request parameter with the Bean property
Suffix used to match the suffix of the request parameter and the Bean property
Attribute scope name.
The fully qualified name of the class of the ClassName actionmapping object is the default
Org.apache.struts.action.ActionMapping
Input enter the path to the form, and point to the control that the bean must return when an input error occurs
Unknown is set to true, the operation will be the default action for all URIs that do not have a defined actionmapping
Validate is set to True, Actionservlet calls the Actionform Bean's Validate () method for input checking before calling the Perform () method on the Action object
The <forward> element enables you to define a logical name for a resource that is the target of the response class's responses to be forwarded.
Attribute description
ID ID
ClassName the fully qualified name of the Actionforward class, which is the default
Org.apache.struts.action.ActionForward
The logical name used by the name action class to access Actionforward
Path of the target resource that the path responds to forwarding
Redirect if set to True, Actionservlet uses the Sendredirec method to forward the resource
3) Configure Actionform Bean
Actionservlet uses Actionform to hold the requested parameters, which correspond to the names in the HTTP request parameters, the controller passes the request parameters to an instance of the Actionform bean, and then the instance is routed to the action class. Example:
<form-beans>
<form-bean name= "Bookform" type= "Bookform"
</form-beans>
Attribute description
ID ID
ClassName Actionform The fully qualified name of the bean, the default is Org.apache.struts.action.ActionformBean
Name of the associated scope of the names form Bean, which is used to associate the bean with the actionmapping
Fully qualified name of type class
4) Configure the JDBC data source
You can define multiple data sources with the <data-sources> element:
Attribute description
ID ID
The Key action class uses this name to find the connection
Type name of the class that implements the JDBC interface
  
The following properties require an <set-property> element definition that is no longer in use in the Struts 1.1 version, but you are available <data-source> elements. For example: |
<data-sources>
<data-source id= "DS1" key= "Conpool" type= "Org.apache.struts.util.GenericDataSource"
<set-property id= "SP1" autocommit= "true" description= "Example Data Source Configuration"
driverclass= "Org.test.mm.mysql.Driver" maxcount= "4"
Mincount= "2" url= "Jdbc:mysql://localhost/test" user= "struts" password= "ghq123"/>
<data-source/>
</data-sources>
  
Attribute description
Description of the Desciption data source
Autocommit The default Automatic Update database schema used by the connection created by the data source
Driverclass the class used by the data source to display the JDBC driver interface
LoginTimeout Database login time limit, in seconds
Maxcount the maximum number of connections that can be established
Mincount the minimum number of connections to create
Password for password database access
Eadonly Create a read-only connection
User name to Access database
URLs for JDBC URLs
  
By specifying a keyword name, the action class can access the data source, for example:
Javax.sql.DataSource ds = Servlet.finddatasource ("Conpool");
Javax.sql.Connection con = ds.getconnection ();
  
   See how struts works from the struts component
  
For struts to control and process customer requests, let us specify this by introducing the four core components of struts. These four components are: Actionservlet, Action classes,action mapping, and actionfrom beans.
  
1) Struts Actionservlet
  
Actionservlet inherits from the Javax.servlet.http.HttpServlet class, its role loses the controller in the struts architecture, the controller Actionservlet mainly is responsible for the HTTP customer request information Assembly, Forwards 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).
  
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.
  
2 Struts Action Classes
  
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).
  
3) Struts actionmapping
  
The relevant information that maps a particular request to a specific action is stored in actionmapping, Actionservelt sends Actionmapping to the perform () method of the Action class, The action uses the Actionmapping Findforward () method, which returns a actionforward of the specified name so that the action completes the local forwarding. If no specific actionforward is found, a null is returned.
  
4) Struts Actionform Bean
  
A non-persistent data store for a message transfer (or state transition) of an application system is maintained by the Actionform Bean.
  
The main function of Actionform is to provide data for action operations that are mapped to a single phase of the Customer table (if, in the case of a customer designation, data is also validated). The action is responsible for maintaining the state of the system data, while the action is responsible for modifying the state of the data according to the needs of the business logic, and after changing the state of the system, Actionform automatically writes back the new data state and maintains it.
  
In the use of actionform, struts advocates the use of value objects. This will enable customers or developers to have a clearer understanding and use of data state and object state.
  
For each client request, the Struts architecture typically undergoes the following steps when dealing with Actionform:
  
① Check the mapping of the action to determine that the action has been configured to map the Actionform;
  
② the configuration information for the form Bean based on the Name property;
  
③ examines the use of the action's Formbean and determines whether an instance of this form bean already exists under this scope;
  
④ If an instance of this form bean already exists in the current scope, but is the same type for the current request, then reuse;
  
⑤ Otherwise, the instance of a form bean is rebuilt;
  
⑥form Bean's Reset () method is called;
  
⑦ invokes the corresponding setter method and assigns a value to the state attribute;
  
⑧ the Validate () method of the form Bean is invoked if the Validatede property is set to True north.
  
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.

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.