Example of a Struts Enterprise Web Development Frame [Reserved]

xiaoxiao2021-03-06  98

Yu Liangsong (reprinted from the open system world) April 25, 2004

Struts is an enterprise-level web application development framework for source code. Its design is to reduce the burden on constructor web application as a whole. This article helps you quickly master Struts in an instance of a Struts application.

Struts is the source code open software developed under Jakarta project, consisting of a series of framework classes, auxiliary classes, and custom JSP tag libraries, positioning J2EE applications based on Model 2 design mode. The Model 2 system is an application of the MVC-View-Controller system. In the MVC system, the data model (Model), the representation, and control logic (Controller) are separate components, but they can communicate with each other. The Struts is trying to reduce the burden of constructor-level web applications as a whole, and provide internationalization and database connection support.

The STRUTS system can be seen as two relatively independent parts: the first part is the Struts API, used to support the Struts application components; the second part is the Struts JSP tag library, four tags of HTML, Bean, Logic and Template composition. Two parts of Struts have their own different users. For items, the same user may use these two parts at the same time;

The Struts design goal is to provide a powerful framework for Model 2 Web application development. At the same time, Struts also contains some practical components, such as Digest, but these components do not partially follow the two parts mentioned above.

Struts application architecture

For those who transfer to Web development from traditional programming environments, a very uncomfortable feature in web programming is the lack of "program". Traditional applications always have primary entrance points, process control, and export points. But on the Web site, users may enter anywhere, access to each page in a completely random order, may even skip multiple pages, or there may be no movement within one or two hours. This is the basic feature of HTTP access, both Struts or other web programming frameworks, cannot be changed. However, Struts hides the Web Access Inherent "confusion" to help developers build clear and clear order and rules.

In the Struts application, there is a home scheduler (or a dispenser) called an ActionServlet, as shown in Figure 1. However, not all requests must pass through the ActionServlet. The user's request target can be a non-Struts page, or a page that uses the Struts tag library but does not use the Struts request allocation service. This is one of the advantages of the Struts system: on demand. Many programming frameworks require you either use, or all, and once you decide, you will pay a high price. Struts The advantages you need to use have formed strong comparisons with such systems.

Figure 1 Request processing in the Struts framework

Struts Application consists of these basic modules:

1. Configuration information;

2.Servlet, mainly struts ActionServlet;

3. Action (Action), execute logic and control (request allocation) function, which is called by ActionServlet;

4.JSP page (belonging to view), often assigned by action class;

5.jsp tag library, use as needed;

6. Various forms of JavaBean, including user-defined JavaBeans. Typical Struts applications To use three profiles: web.xml, struts-config.xml, and optional application resource files.

Web.xml is a standard configuration file for web applications, which is the components required for all J2EE web applications. The application server maps the URL to Servlet and JSP via this profile, and the startup parameters are specified for servlet and JSP via this profile. The basic web.xml file provided for the Struts application is simple, and there is only one master ActionServlet definition, and a mapping that makes sure the Struts request passes to the ActionServlet. According to the convention, the URL ends ended with ".do" is Struts request, such as /login.do. The application server uses the mapping in the web.xml file to the ActionServlet. Next, the ActionServlet determines how to assign the request. The ActionServlet decision is based on the rules defined in Struts-Config.xml, and / or distributes the allocation logic defined by the ActionServlet.

Struts-config.xml is called a struts profile. The Struts application is a network that relies on the struts-config.xml file to connect components. The Struts-Config.xml file defines the logical name for the component of the web application, which defines their properties and relationships under the Struts framework, just like the web.xml file defines the components within the web application framework. The Struts-Config.xml file contains application information related to the Struts framework, which is divided into four classes:

1. Data source information, it is optional. Here you can specify one or more JDBC data sources so that the database definition information is concentrated. For database access, Struts also has an additional advantage that supports basic database connection pool features.

2. Form bean is a special type of JavaBean, which simplifies the processing of the web form.

3. Global Forwards are global forwarding definition information. The Struts action runs according to a "request-forward" mechanism. In order to minimize the action module and forwarding target, a mapping mechanism is used, allowing the forwarding target by synonym reference. Some target pages may be referenced by multiple action classes, such as login page, so you can map the logical target page to the physical target page in the global forwarding definition section to avoid adding this part of the information to the action definition section.

4. Actions defines the request allocation information of the Struts application system, which is the supplemental definition of the core distributor, which is responsible for processing various specific request types.

A simple application

Struts-based web application and normal web applications have many equations, but Struts applications also have their own special needs. A deployable web application should organize and form a WAR file. The WAR file is a JAR package with the directory structure shown in Figure 2. For Struts Web applications, add some additional files, such as Struts-Confg.xml files, and tag library descriptors (TLD) files in the web-infl directory. Note: The application's resources should be placed in the application's class path, which is the web-inf / lib directory or the JAR package under the web-inf / class directory. For most simple Struts pages, we only use the Struts tag library, and the terminology of MVC does not need to be involved in the Model and Controller section, which only involves View. Please see the home page example shown in Figure 3. Although this page does not have a form, Struts is still able to help when designing this page.

Figure 2 Directory structure of the Struts application

Figure 3 A simple view

To manage sessions, the easiest way is to use cookies. After the session identifier is passed to the client, the client saves it to the cookie, and the cookies are sent to the server each time the request. However, like many other Web solutions, the cookie solution is not universal, because some users may not trust cookies, close the browser's cookie support. Due to this situation, the URL rewriting technology will appear. When using the URL to change technology, all the session identifiers will be added later throughout the URL of the entire website. Although this program is not as simple as using a Cookie scheme, it does do it. URL rewriting technology is unstable to have two reasons. First, and the cookie is different, the URL has no expiration time. If a URL with a session ID is intercepted, it will be used in future access, then this URL will not be useful, because the session generally is at a certain time Void. Secondly, if there is a session identifier after a URL link, the entire chain will be interrupted, and the client cannot obtain the session identifier again unless it backs up the URL access history with the session identifier. The servlet can complete the URL to write only by one method call. Technically, JSP can also do this, but a good JSP page should not contain Java code, or contain as little Java code. To do this, Struts provides a link tag. This example uses the tag to maintain session status information between the client and the server.

Bind View, Model and Controller

The previous simple page does not require a Struts dispenser because it is only a simple link. Figure 4 shows a more complex "category" page. It lists the category entries in the database and links these entries to the corresponding editing page. To display this page, we have to use the Struts an ActionServlet allocation mechanism.

Figure 4 Category page

In the web.xml file, put it into a declaration that the URL request ending with ".do" must be sent to the Struts distributor. The dispenser here can be org.apache.struts.Action.ActionServlet or its extended class. The STRUTS dispenser reads the struts-config.xml file at startup and constructs a motion map. This example specifies a working class called showcategories to handle the "showcategories" action. It can be seen that the basic working mode of the Struts application is: the main dispenser calls an action allocator, the action splitter determines or constructs the Model section (a JavaBean or other Java object) and supplies it to the View (usually a JSP page).

This example is slightly complicated using bean. It has multiple data items, so we don't use a single-providing data to be available, but to generate a set of beans. Unfortunately, the JSP page is based on HTML, and HTML does not provide loop or other control logic. However, Struts's logic: Iteerate allows an array to be iterative, as shown in the following code segment:

Edit Delete < / html: link> discussed the Model 2 system of Model 2 system Let's take a look at the Controller section. The Struts system has a primary controller, namely ActionServlet. The ActionServlet is responsible for selecting and calling the appropriate action controller - the extension class of org.apache.struts.Action.Action. The action controller implements the Process () method. The process () method analyzes each parameter that is incorporated from the URL, performs the necessary business logic, and returns an action specified in the call chain (usually a view). In this example, we want to extract data from the database, create JavaBean managed to manage these data, hold multiple JavaBeans into an array, then save the array to the requested context, so that the page can be easily performed as a view of the View layout.

In order to ensure the smooth operation, add a declaration in the struts-config.xml file, specify which action processor to process the specified action:

Form processing

The form processing process fully reflects the advantage of Struts. In web applications, most of the complex HTML processing tasks involves the form. The form editing process has the request or response structure similar to Figure 5. The process of updating the operation is similar to the process of creating operations, but for update operations, "Creating Model" steps into "load model", and "saving model" becomes "update model". Note the feature of the web application: The operation process may be suspended at any time, which may be because the user cancels the current operation by the explicit action, or because the user does not submit a form, for example, the user jumps to one is not used to handle the current The URL of the form.

Figure 5 Form processing flow

The form editing process is divided into three phases: here respectively refer to Preparation, Presentation and Storage. The preparations and storage phases belong to the Struts action, and the performance phase is mainly the client's activities. Table 1 shows the various components involved in the process: Form Bean is a special JavaBean type, which simplifies form processing. Form bean is extended from org.apache.struts. Action.Actionform class. Form bean has several useful features, for example, through the reset () method can set the properties of the bean to the default value, allow the bean to verify the legality of the property through the validate () method. More importantly, the ActionServlet ensures that the Form Bean is created and can be called for its action method. The HTML tag library is also capable of ensuring that the Form Bean is properly initialized and data is obtained from the Form View.

The Form Bean should belong to the Model section, however, since it has a validate () method, it is closer to the dispenser from some features. However, there is no need to care too much about these concepts. Model 2 is not completely equivalent to MVC, and some people have suffered a mixture of simple design patterns in the blame MVC. In any case, from the perspective of application practices, the system's stability is more important than the strictness of the concept. In this case, this problem is more representative because we also package the persistence mechanism into the Form Bean. From a technical point of view, the deposit of Bean data is a view, so in this sense, we now have a model combined with the dispenser and view characteristics. This design looks seems to negate the reasons for the introduction of the Struts, but in fact, this design is characterized by the characteristics of many regrets.

First, since the verification code and SQL code are largely dependent on the properties owned by the Form Bean, they have brought great convenience as a unit management. Because only interested in FORM beans, "heavyweight" distributors and view components are valid. Second, the Form Bean is used with the HTML tag library, the Form bean can contain other objects. These objects can be applied by "." Symbol. When using a predefined Java object, "." The reference method can bring great convenience because Java does not support multiple inheritance. "." The reference method avoids the complicated work of hand-written a large number of GET / SET code.

When the internal object is EJB, "." The convenience brought by the reference method is more prominent, because EJB tends to be "cumbers" when references EJB in the JSP page. If EJB is embedded in the Form Bean, many regrets in this area no longer exist. More importantly, it separates the Controller and Model, and the view persistence is also simpler as the simplest extent, as the EJB container can handle details of all persistence. In this way, Form Bean has almost a purely distributor, and everything becomes clean and clear.

If the EJB has a lot of properties, and according to the ActionServlet, it will be updated in a manner that each attribute is updated, and there will be a large number of RMI call overhead. For higher applications, a better choice is to utilize EJB 2.0 local interfaces, or add a traditional JavaBean (usually session EJB) before EJB, and pass the bean to the entity bean's UpdateAllProperties () business method. The following scheme allows all updates to be completed in a single RMI call. Preparation Phase

A typical editing session requires an action processor to prepare View, which is a JSP page as a view, and requires a second action processor to store updated View. Of course, there will be a page that is a page belonging to a view after the storage operation (see Table 1) is displayed, for example, a "data has been updated.

Table 1: Parts to be used based on Form bean

Component Description Catalogform Form Bean EditcateGoryAction Preparation Phase Editcategory.jsp Edit SavecateGoryAction Storage Phase EditDone.jsp Confirm Data Save EditFailed.jsp "Data No Save" error

The following code snippet shows how to configure the preparation stage in the struts-config.xml file:

In the preparation phase, the container attempts to find the specified form bean from session or request, because "Name = ..." is specified in the action. The ActionServlet looks for the Struts-Config.xml file area to find the alias of Form Bean, and use the form of the Form Bean to find the corresponding Java class. If the user's request with parameters, its name matches the parameter of the FORM BEAN attribute name will be set to the attribute value. The Struts extends the meaning of the "Property Name", making the properties of the access to the Form Bean embedded objects possible. The examples of this article also use this advantage of Struts.

After preparing the Form Bean, the ActionServlet then calls the action process () method, the Form Bean is incorporated into the Process () method. Here, our final adjustment of the Form Bean, calls the business method, delegates the editcategory as a view to generate a HTML page based on the form bean. This page is passed to the client, and then the "performance" phase will be entered.

Performance phase

This phase of the user edits the form and submits. If the server is applied to the content of the server, there is a problem with the content submitted, it displays the form to the user, plus the appropriate prompt information; repeat the process until the user submits a legal form, or cancels the form processing process. The suspension of the editing process may be due to the user's jump to other pages, or start a cancel action (for example, a button defined by the HTML: Cancel tag). Although in theory, the VIEW's verification and re-display operation should be a stage of expression, but in the Struts application, this part of the function is most convenient in the storage phase. Storage phase

The preparation phase creates actions CATForm with the "name =" attribute defined, and the storage phase is added to the additional attribute, namely "validate = 'true'" and "input =" attributes.

After setting the "validate = 'true'" property option, the server will add a processing step. Re-use the data from view to the FORM bean, or when updating from bean, the FORM BEAN's validate () method is called. The validate () method performs the necessary legitimacy verification operations. If there is an error in the user's input data, the validate () method creates one or more ActionError objects. These ActionError objects contain the name of the error message ID and form input field. These ActionError objects are collected and sorted into an ActionerRors object, and then the ActionerRors object returns by the validate () method. If the data entered by the user does not include an error, Validate () returns NULL.

Since the "Input =" property is specified, the action will be ignored once an error occurs, and the "INPUT =" specified by the VIEW is displayed. This view contains both Form Beans, also contains the currently incorrect object collection. Generally, this input page is the JSP page that originally performs editing functions.

Most Struts's HTML tag has a corresponding HTML mark, but Struts has an HTML that is not marked, ie tag. To abort the form editing process, the user can manually enter the URL, or you can click on the link not point to the storage action processor. Therefore, the "Cancel" button defined with the tag is not the only way to cancel the editing operation.

Suppose the validate () method does not find any errors, and the user does not click the "Cancel" button, the process () method of the storage action will be called. In this process () method, we call the Form Bean's Save () method to write the data into a persistent storage device, and then display "Successful" Successful "or" Storage Action Failure "is displayed based on the write operation. VIEW.

Construct and run Struts application

To construct and run the sample application of this article, you must learn how to use Jakarta's Ant tools. If you still don't understand Ant, it is time to learn it! Hurry to the website to download Ant, usually unwind to compress, set up Ant_home environment variables, and then add Ant to the execution path. The build.xml of this article needs to be customized slightly, modify the configuration of the local Tomcat location, enabling it to find the class necessary to compile under Tomcat. In addition, you have to have a struts of JAR. You can download the latest version.

The struts-config.xml file is a configuration file that bonds the Struts application. In a web application after deployment, struts-config.xml is in a web-infirectory. You should modify the data source configuration so that it meets your current DBMS environment. The data model and SQL schema files are written for PostgreSQL DBMS in the DBMS directory of the download package.

In the example, SRC / COM / STRUTSDEMO / SHOWCATEGORIESATION. JAVA is a simple dispenser. ActionForward () is a request allocation method that is called from an ActionServlet. This method can complete the main work, such as analysis request parameters, perform calculations, and JavaBean constructing VIEW. In addition, the method also determines what page to display according to the result of the processing: It may be one of the plurality of pages of the preset, or an error message page.

ActionForward () request allocation process

Of course, the most complex processing procedure is related to the form. The request allocation process for the ActionForward method is:

1. ActionServlet, decoding the request. Since the Form Bean is specified for the action, the ActionServlet processes the Form Bean (see "How to use the ActionServlet how to use Form bean"). Then, the request is passed to the EditCateGoryAction.

2. EditcategoryAction; Prepare the process of processing, or from the database into existing data, or create a new data item. The action processor uses mapping.forward to pass the control to editcategory.jsp.

3. DITCATEGORY.JSP shows the Form Bean, allowing users to edit data. After the user submits the data, control to the ActionServlet.

4. ActionServlet, decode the request. This time, the Form Bean will initialize the data of View because it is a Struts JSP table single page. Due to the Form Bean, "Validate = 'True'" is specified in Struts-Config.xml, the validate () method of the FORM BEAN name "CATFORM" is called. If the data submitted by the user cannot be verified by legality, the control is turned to editcategory1.jsp.

5. Editcategory1.jsp, it is just a version after editcategory.jsp. If necessary, the original editing page and the editing page with the error prompt can use the same view. The Struts JSP tag can help us do this easily. This page is submitted to /savecategory.do. In this way, the user has a circle between these pages until he jumps to a page that is not related to editing operation, or the data he submits is verified by legality.

6. If the Form Bean legality is verified, the ActionServlet passes the request (including Form Bean) to SavecategoryAction. In this example, "Save" may mean create an operation, which may also mean the update operation, which is determined by the option provided by the URL. The operation of writing data is done by calling the Store () method of the Form Bean. Note: The actual application should use some type of transaction management mechanism (or use EJB because EJB has built-in transaction management mechanism) to avoid concurrent access. How to use Form Bean using formalvlet

The ActionServlet process involving the Form Bean contains six steps:

1. Find or create form bean;

2. According to the corresponding data incorporated from the HTTP request, update the various properties of the FORM BEAN;

3. Check if the user clicks the "Cancel" button. If it is skipped, steps 4 and 5;

4. Verify the legality of Form Bean data;

5. If the data is not verified by legality, the VIEW specified in the "Input =" parameter is sent;

6. Otherwise, pass the Form Bean to the action processor.

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

New Post(0)
CopyRight © 2020 All Rights Reserved
Processed: 0.042, SQL: 9