Struts 1.1

xiaoxiao2021-03-06  94

As the MVC mode, the most classic framework is formally launched, and the version provides many exciting new features on the past versions. This article will take you into struts 1.1 to understand these features in depth.

Note: It is hoped that the readers in this article can have a certain Struts use basis.

1, MODEL 2

Struts is based on Model 2, and Model 2 is a web application variant of a classic MVC (Model-View-Controller) model. This change is mainly caused by the state of the network application - the state of state of the HTTP protocol. . The purpose and MVC of Model 2 are also used by controllers to separate models and views to achieve an effect of lamination coupling, improve system flexibility, reuse and maintainability. In most cases, you can equate Model 2 with MVC.

The figure below shows a typical network application based on Java technology, which can be seen from the various parts of Model 2 corresponding to various prior art in Java.

Before using Model 2, we set all the logic and business logic (such as gods like JSP), sometimes calling this application mode for model 1, Model 1's main disadvantage is to follow, multiplexed Sexy difference and high maintenance cost.

2, Struts 1.1 and Model 2

Since Struts 1.1 is above Model 2, its underlying mechanism is MVC, the following is a schematic diagram of the MVC implementation in Struts 1.1:

Illustration: Where different colors represent different parts of the MVC: red (controller), purple (model) and green (view)

First, the controller (ActionServlet) performs initialization, reads the configuration file (struts-config.xml), initializing the corresponding moduleconfig object for different Struts modules. For example, the Action mapping definition in the configuration file is saved in the ActionConfig collection. There is a ControlConfig collection, a FormBeanconfig collection, a ForwardConfig collection, and a MessageResourcesConfig collection.

Tip: The module is a new concept in Struts 1.1. In the later content, we will introduce, you can now simply think of a subsystem as a subsystem, and they integrate the entire application, and they are independent. All processes in Struts 1.1 are done in a particular module environment. The module proposes to solve the problem of Struts 1.0 in the SF configuration file.

The controller receives the HTTP request and identifies the Action subclass corresponding to the request from ActionConfig. If there is no corresponding action, the controller directly forwards the request to the JSP or static page. Otherwise, the controller distributes the request to the specific Action class for processing.

Before the controller calls the specific Action's Execute method, the ActionForm object will use the parameters in the HTTP request to populate yourself (optional steps, need to specify in the configuration file). The specific ACTIONFORM object should be a subclass of ACTIONFORM, which is actually a JavaBean. In addition, the validate method can be called in the ActionForm class to check the legality of the request parameter, and can return an ActionerRors object containing all error messages. If the execution is successful, the ActionForm automatically saves these parameter information in a JavaBean (generally referred to as form bean) in servlet context so that they can be called by other Action objects or JSP. Struts is placed in the FormBeanconfig collection in the FormBeanconfig collection, and you can know if a customer request needs to create a corresponding Actionform instance.

Action is simple, usually only one Execute method, which is responsible for performing the corresponding business logic, if necessary, it also performs a corresponding data check. After the execution is complete, return an ActionForward object, and the controller is forwarded by the ActionForward object. We advocate that the function of obtaining data and executing business logic is placed in the specific JavaBean, and Action is only responsible for completing the functions related to control. Follow this principle, so I am in the above picture to classify the Action object as the controller section.

Tip: In fact, in Struts 1.1, the role of actionmapping can be replaced by ActionConfig, but because it is a part of the public API and the problem of compatibility is reserved. ActionMapping gets the same functionality by inheritance ActionConfig, you can consider them. Similarly, the relationship between other, for example, ActionForward and ForwardConfig is true.

The figure below gives a graphical description of the client from the issuance request to get the response.

Let's discuss each of them in detail, before this, let's take a look at the concept of the module.

3, module

We know that in Struts 1.0, we can only specify a configuration file for the ActionServlet in Web.xml, which is certainly no problem in our online teaching example, but in the actual application development process, there may be some troublesome . Because many developers may also need to modify the configuration file, but the configuration file can only be modified by one person, so it will definitely cause a certain extent, which will inevitably affect the development efficiency and the complaints of developers.

In Struts 1.1, in order to solve this problem of parallel development, two solutions are proposed:

Support for multiple configuration files

Support multiple profiles means that you can specify multiple XML configuration files for ActionServlets, and files between files, such as the MailReader presentation example provided by Struts.

Action

org.apache.struts.Action.ActionServlet

config

/web-inf/struts-config.xml, /web-inf/struts-config-registration.xml

1

This method can solve problems with conflicts, different developers can set their own action, Actionform, etc. in different configuration files (of course, not, each developer needs their own configuration file, can follow the system Function module is divided). However, there is still a potential problem, that is, there may be conflicts between different configuration files, because the few files will eventually merge together when the ActionServlet is initialized. For example, in Struts-Config.xml, a "Forward" named success is configured in Struts-Config-Registration.xml, it is also configured to conflict.

In order to completely solve this conflict, the concept of module is introduced in Struts 1.1. A module is a separate subsystem that you can perform any of the required configurations, but also don't have to worry about conflicts with other profiles. Because we talked, ActionServlets were saved in different module information in different moduleconfig objects. To use the functionality of the module, you need to do the following preparations:

1. Prepare a configuration file for each module

2, configure the web.xml file, notify the controller

Decide that after using multiple modules, you need to tell the controller, which needs to be configured in the web.xml file. Below is a typical multi-module configuration:

config

/web-inf/struts-config.xml

config / customer

/web-inf/struts-config-customer.xml

config / order

/Web-inf/struts-config-order.xml

To configure multiple modules, you need to increase the of the module on the original (referred to in Struts 1.1 to the default module). Where is in the form of config / xxx, where xxx is the corresponding module name, or the configuration file corresponding to the module. The above example shows that the application has three modules, which are default modules, Customer, and Order, which correspond to different profiles.

3. Prepare resources such as ActionForm, Action, and JSP required for each module

However, it should be noted that the appearance of the module also brought a problem, that is, how to forward between different modules? There are two ways to realize the forwarding between modules, one is defined in (globally or local), and the other is to use org.apache.struts.Actions.SwitchChaction. Below is a global example:

...

...

ContextRelative = "true"

PATH = "/ Moduleb / INDEX.DO"

REDIRECT = "true" />

...

...

It can be seen that only the module name needs to be added prior to the original Path property, and the ContextRelative property is set to true. In addition, you can define a similar local in .

TYPE = "com.ncu.test.loginaction"

Name = "loginform"

Scope = "request"

Input = "tile.userlogin"

Validate = "True">

If you already in other modules, you need to turn back to the default module, which should be similar to the following, that is, the module name is empty.

In addition, you can also use org.apache.struts.Actions.switch, for example:

...

TYPE = "org.apache.struts.Actions.switch" />

...

...

4, ACTIONSERVLET

Let's first understand the controllers in the MVC. The ActionServlet class is used to act as a controller in the default in Struts 1.1. Of course, if the ActionServlet does not meet your needs, you can also implement your own class by inheriting it. This can be specified in /Web-inf/web.xml.

To master an ActionServlet, you must understand the role it played. First, the ActionServlet represents the controller part in the MVC structure, which requires duties to complete the front-end control and forwarding requests required for the controller. Second, ActionServlet is implemented as a servlet that deals with HTTP requests, which has the characteristics of servlet. In Struts 1.1 It mainly completes the following features: Receive the client request to map the request to a corresponding Action class according to the client's URI to get the data population form bean (if needed) Call the action class EXECUTE () method Get data or Perform business logic Select the correct view response

In addition, the ActionServlet is also responsible for initializing and clearing the task of applying configuration information. The initialization of the ActionServlet is completed in the init method, which can be divided into two parts: initialize some of the information of the ActionServlet itself and the configuration information of each module. The former is mainly done primarily through the three methods of initinternal, initother, and initservlet.

We can specify specific controllers and initial parameters in /Web-inf/web.xml, and some initial parameters are discarded or moved into / web-inf / struts-config due to the change of version changes and the introduction of module concepts in Struts 1.1. . XML is defined in. All discarded parameters are listed below, and they are not encouraged in the Web.xml file accordingly.

Application Buffersize Content Debug Factory Formbean Forward Locale Mapping MaxFileSize MultipartClass Nocache Null Tempdir

ActionServlet initializes the ModuleConfig class according to different modules, and saves the various configuration information of the module in the way in XXXConfig collection, such as ActionConfig, FormBeanConfig, etc.

After the initialization work is completed, the ActionServlet is ready to receive a customer request. For each request, method Process (httpservletRequest request, httpservletResponse response) will be called. This method specifies the specific module and then calls the processProcessor of the module.

Protected Void Process (httpservletRequest Request,

Httpservletresponse response

THROWS IOException, servletexception {

Requestutils.SelectModule (Request, GetServletContext ());

GetRequestProcessor (GetModuleConfig (Request)). Process (Request, Response);

}

RequestProcessor contains all processing logic of the Struts controller, which calls different processxxx methods to complete different processing. The following table lists several of the main methods:

The method of obtaining the function processPath processMapping client request path using the path to obtain the corresponding ActionMappingprocessActionForm ActionForm execute the initialization process (if necessary) and stored in the proper scope processActionCreate ActionprocessActionPerform call initialization process the ActionForward Action Action of return processForwardConfig

5, Actionform

For ActionForm, you can understand it from the following aspects:

ActionForm represents data in the HTTP form, which can be seen as an intermediary of models and views, which is responsible for saving data for models or views in the view. The Struts 1.1 document is compared to the firewall between http and action, which reflects the role of the ActionForm has the effect of filtering, and only data verified by ActionForm can be sent to the action processing. The ActionForm is a JavaBean associated with one or more ActionConfig. Before the corresponding action Execute method is called, the ActionForm automatically fills yourself (initialization properties). ActionForm is an abstract class that you must implement your own class by inheritance. ActionForm first uses attributes getter and setter methods to implement initialization. After initialization, the ActionForm's Validate method is called, you can check the correctness and validity of the request parameter, and you can return the error message to the form of ActionerRORS. Enter the form. Otherwise, ActionForm will be transmitted to an Execute method for parameters for use.

The lifecycle of the ActionForm bean can be set to session (default) and request, when set to session, remember to reset all attributes to the initial value in the reset method.

Since the Actionform corresponds to the HTTP form, your ActionForm will increase sharply with the increase of the page. And it is possible that the same type page field will appear in different ActionForms and there is the same verification code in each ActionForm. To solve this problem, you can implement an actionform or at least one module for an ActionForm for the entire application.

However, the cost of polymerization is very poor reuse, and it is difficult to maintain. In response to this problem, the concept of DynaActionform is proposed in Struts 1.1.

DynaActionform class

The purpose of DynaActionForm is to reduce the number of ActionForm, which you don't have to create a specific Actionform class, but configure the desired virtual ActionForm in the configuration file. For example, create a dynamic actionform - loginform by specifying type as "org.apache.Action.Action.DynaActionform" by specifying Type.

Dynamic ActionForm uses the same as normal ActionForm, but pay attention to it. Ordinary Actionform objects need to provide Getter and Setter methods for each property. In the above example, we need to provide the getUserName () and setUsername () methods to get and set the username property, and have a pair of methods for obtaining and setting Password. Properties and ActionClass properties. If you use DynaActionform, it saves the property in a HashMap class object while providing the corresponding GET (NAME) and SET (NAME) method, where the parameter NAME is the name of the attribute to access. For example, to access the value of the username in DynaActionform, you can use similar code:

String username = (string) form.get ("username");

Since the value is stored in an HashMap object, it is necessary to remember to make mandatory type conversion to the Object object returned by the GET () method. It is because of this difference, if you use the Actionform object very frequently in Action, it is recommended to use a normal ACTIONFORM object.

In Struts 1.1, in addition to DynaActionForm, a form of automatic authentication is provided, providing many useful classes in the package org.apache.struts.valiDator, where the most common is the DynavalidatorForm class.

DynavalidatorForm class

DynavalidatorForm is a subclass of DynaActionform, which provides features for dynamic ActionForm and automatic form input verification. Similar to DynaActionForm, you must first configure in the configuration file:

At the same time, you want to define the verified plugin:

Value = "/ Web-inf / validator-rules.xml,

/Web-inf/Validation.xml "/>

The validator.xml and validator-rules.xml represent the contents of the authentication definition and verification rules (which can be merged together), such as DynavalidatorForm in the previous example, we have the following verification definition (Validator.xml):

"- // Apache Software Foundation // DTD Commons Validator Rules Configuration 1.0 // En"

"http://jakarta.apache.org/commons/dtds/Validator_1_0.dtd">

maxices> Maxlength

16

minlength

3

maxices> Maxlength

16

minlength

3

From the above definition, we can see that there are three validations for the field Username: Required, MINLENGTH, MAXLENGTH, meaning that the field cannot be empty, and the length is between 3 and 16. The Validator-Rules.xml file can use the default file provided by Struts. Note How the FORM defined in is associated with the Form in Validation.xml. Finally, to start the automatic verification function, you also need to set the validate property of the Action configuration to True.

TYPE = "com.ncu.test.loginaction"

Name = "loginform"

Scope = "request"

Input = "Tile.userLogin" Validate = "True">

At this point, Struts will verify the form input according to the definition in the XML configuration file and output the error message that does not meet the requirements to the page. But you may think: This feature is good, but what is the inspection that runs to the server-side execution, efficiency, and user easy-to-use, is it some problem? You may miss the simple JavaScript client verification.

Don't worry, JavaScript client authentication is also supported in Struts 1.1. If you have selected the client authentication, after a form is submitted, Struts 1.1 launches the client verification. If the browser does not support JavaScript verification, the server-side verification is started, which can maximize the maximum satisfaction Developers' needs. JavaScript verification code is also defined in the validator-rules.xml file. To start the client authentication, you must do the following settings in the appropriate JSP file:

Add the onSubmit property to set the onSubmit property to set up JavaScript support for

The sample code of a JSP file is listed in the following table, and the red word part is JavaScript verification code.

<% @ Taglib URI = "/ Web-INF / STRUTS-HTML.TLD" prefix = "html"%>

Panel 3: Profile


>>>>>>>

UserName:

Password: