[Post] struts

Source: Internet
Author: User
Struts was first launched as part of the Apache Jakarta project. The project creator hopes to improve and improve the technical standards of Java Server Pages, Servlet, label library, and object-oriented through the study of this project.

The struts name comes from the supported metal racks used in buildings and old-style aircraft. It aims to reduce the time needed to develop Web applications using MVC design models. You still need to learn and apply the architecture, but it will do some heavy work.

Like many Apache projects such as Tomcat and turbine, Struts is an open-source software, which provides developers with a deeper understanding of its internal implementation mechanism.

In addition, the advantages of struts are mainly embodied in two aspects: taglib and page navigation. Taglib is a struts tag library, which can be used flexibly to greatly improve development efficiency. In addition to common JSP tags, JSP developers in China rarely develop their own tags. Struts may be a good starting point.

As for page navigation, I think that will be a future direction. In fact, this will make the context of the system clearer. With a configuration file, you can grasp the relationship between all parts of the system, which is of great benefit for later maintenance. This advantage is especially evident when another group of developers take over the project.

MVC, short for Model-View-Controller, is a common design pattern. MVC weakens the coupling between the business logic interface and the data interface, and makes the view layer more changeable. Struts is an implementation of MVC. It uses Servlet and JSP tags (belonging to the J2EE specification) as part of the implementation. Struts inherits various MVC features and makes corresponding changes and extensions based on J2EE features. How struts works ,:

Struts Framework
The Struts framework has the advantages of modular components, flexibility and reusability, and simplifies the development of MVC-based Web applications.
This chapter discusses the struts architecture in detail. We will see how struts clearly separates control, transaction logic, and appearance, thus simplifying the process of developing applications. We will also introduce how Struts provides classes to make development easier. These classes include:
Control Program Flow class
Class for implementing and executing program transaction logic
Custom tag library makes it easier to create and verify HTML Forms
1. Struts compressed Package content
The folder jakarta-struts-1.0.2 contains two directories: Lib and webapps. The following files are required to create an application using struts in the lib directory:
File description
Jdbc2_0-stdext.jar contains the jdbc2.0 Optional package API class. If we want to use the data resources provided by struts, We need to copy this file to WEB-INF/lib
Struts. jar contains all Java classes in struts. Also need to copy to WEB-INF/lib
* The TLD tag library descriptor file describes the custom tags in multiple struts tag libraries. Also to copy to WEB-INF/lib
The webapps directory contains the following files:
Web application description
Struts-blank.war a simple Web Application
The Struts-documentation.war contains all struts documents on the struts site
Demonstration of many characteristics of Struts-example.war struts
The Struts-exercisetaglib.war is primarily used to add and use test pages for the custom tag library, but it can also demonstrate how to use struts tag
Introduction and example of Struts-template.war containing struts template tag
A simple example of Struts-upload.war to demonstrate how to use Struts framework to upload files
2. Struts Architecture
Let's look at the components in the Struts framework from the MVC perspective.
The framework consists of three parts: model, window, and controller.
Model
In the Struts framework, the model is divided into two parts:
Internal system status
Operations that can change the status (transaction logic)
The internal status is usually represented by a group of actinform JavaBean. Depending on the design or application complexity, these beans can be self-contained and continuous, or only obtain data (from a database) as needed ).
Large applications typically encapsulate transaction logic (Operations) within a method, which can be called by bean with state information. For example, the shopping cart bean has the information of the purchased items, and the checkout () method may be used to check the user's credit card and send the order information to the warehouse.
In small programs, operations may be embedded in the action class, which is part of the controller role in the Struts framework. This method is suitable when the logic is simple.
We recommend that you separate the transaction logic (what to do) from the role played by the action class (what to do.
Windows
Created by JSP, Struts contains the extended custom tag library, which simplifies the process of creating a completely internationalized user interface.
Controller
In struts, the basic Controller component is the instance servelt in the actionservlet class. The actually used servlet is defined by a group of mappings (described by the actionmapping class) in the configuration file.
3. Components in the Struts Framework

(Because the Rose tool has not been downloaded, you can only find this image. It illustrates some problems, especially actionerrors, but it does not include actionmapping, JSP, and tag library, so it has time to complete the replacement)
Components used in the framework:
Actionservlet Controller
Actionclass contains transaction logic
Actionform display module data
Actionmapping helps the Controller map requests to operations
Actionforward indicates the object to be transferred
Actionerror is used to store and recycle errors.
Struts tag library can reduce the development and display Layers
Next, let's take a look at the roles and responsibilities they play in the framework.
3.1 struts configuration file
This is something that combines struts components: struts-config.xml. Default Value
WEB-INF/struts-config.xml. The configuration file can be defined as follows:
Global Forwarding
The actionmapping class helps the Controller map requests to operations.
Actionform bean display module data
JDBC Data Source
Configure Global Forwarding
Global Forwarding is used to create logical name ing between JSP pages. Forwarding can be obtained through the instance mapped to the call operation, for example:
Actionmappinginstace. findforward ("logicalname ");
Example of Global Forwarding: (I have not explained all the examples. First, we can understand them in combination with tables. Second, most examples come from series 4 examples. After completing the experiment, let's take a look)
<Global-forwards>
<Forward name = "bookcreated" Path = "/bookview. jsp"/>
</Global-forwards>
Attribute description
Name: name of Global Forwarding
Relative Path of path and target URL

Configure actionmapping
Actionmapping objects help to control the internal process of the framework. They can map request URIs to the action class and associate the action class with the actionform bean. Actionservlet uses these mappings internally and transfers controls to instances of specific action classes. All action classes use the perform () method to implement specific application code and return an actionforward object, including the target resource name for response 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
Path relative path of the action class
Name: name of the Action bean associated with this operation
Full name of the action class connected to the ing of type (package name available)
Scope actionform bean scope (request or session)
Prefix is used to match the prefix of the request parameter and bean attribute.
Suffix is used to match the suffix of the request parameter and bean attribute.
Attribute scope name.
The default class of the fully qualified class of the classname actionmapping object is org. Apache. Struts. Action. actionmapping.
Path of the input form, pointing to the control that must be returned when an input error occurs in the bean
If unknown is set to true, the operation will be used as the default operation for all undefined actionmapping Uris.
If validate is set to true, actionservlet will call the validate () method of actionform bean to check the input before calling the perform () method on the Action object.
You can use the <forward> element to define the logical name of a resource, which is the target of the action class response to be forwarded.
Attribute description
ID
The fully qualified name of the classname actionforward class. The default name is org. Apache. Struts. Action. actionforward.
Name the logical name used by the operation class to access actionforward
Path: the path of the target resource to be forwarded.
If redirect is set to true, actionservlet uses the sendredirect () method to forward resources.

Configure actionform Bean
Actionservlet uses actionform to save the request parameters. The attribute names of these beans correspond to the names in the HTTP Request Parameters. The controller passes the request parameters to the actionform bean instance, then, the instance is sent to the action class. Example:
<Form-beans>
<Form-bean name = "bookform" type = "bookform"/>
</Form-beans>
Attribute description
ID
The fully qualified name of classname actionform bean. The default value is org. Apache. Struts. Action. actionformbean.
Name form bean name in the relevant scope. This attribute is used to associate bean with actionmapping.
Fully Qualified name of type class

Configure the JDBC Data Source
You can use the <data-sources> element to define multiple data sources.
Attribute description
ID
The key action class uses this name to find connections.
Type indicates the name of the JDBC interface class.
The following attributes must be defined by <set-property> elements. They are no longer used in Framework 1.1, but you can use <data-source> elements. 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 = "wrox"/>
<Data-source/>
</Data-sources>
Attribute description
Description of the desciption Data Source
The default automatic update database mode for connections created by the autocommit Data Source
The class used by the driverclass data source to display the JDBC driver interface.
Logintimeout database logon time, in seconds
Maximum number of connections that can be established by maxcount
Mincount: Minimum number of connections to be created
Password for database access
Readonly creates a read-only connection
Username used by the user to access the database
URL: JDBC URL
By specifying the 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 ();

3.2 actionservlet class
The Controller component in the framework is implemented by the org. Apache. Struts. Action. actionservlet class, which is an extension of the javax. servlet. http. httpservlet class.
The basic functions of struts controller are as follows:
1. Intercept users' HTTP requests
2. Map the request to the corresponding action class. If this is the first request received by this class, the instance will be initialized and
Slow.
3. Create or discover an actionform bean instance (check whether the configuration file is defined), and then port the request process
Bean.
4. Call the perform () method of the Action instance and call the actioform bean, Action mapping object, request
And response object to it.
For example, public actionforword perform (actionmapping mapping,
Actionform form,
Httpservletrequest request,
Httpservletresponse response)
5. Perform returns an actionforword object, which is connected to the corresponding JSP page.
Actionservlet Configuration
We need to declare actionservlet in Web. xml and configure it for loading at startup. The following are configurable initialization parameters:
Default parameter description
Application null class of the application's resource set
Buffersize 4096 buffer size for File Upload
Config/WEB-INF/struts-config.xml profile location and name
Default content type of content text/html
Debug 0 program debugging level
Level of detailed program debugging in detail 0
Factory Null message resource factory, used to interpret Message Resources in international market
Formbean org. Apache. Struts. Action. actionformbean name of the class that encapsulates actionform bean Information
Forward org. Apache. Struts. Action. actionforward name of the class that encapsulates the information of the actionforward object
If locale is true, a local object is stored in the user session.
Mapping org. Apache. Struts. Action. actionforward class name that encapsulates actionmapping Information
Maxfilesize 250 m maximum size of the uploaded file
Multipartclass org. Apache. Struts. Action. actionforward name of the class for processing multiple requests
Nocache false whether the HTTP header must be set to Disabled
Null true is set to true. If the keyword is invalid, null is returned.
Tempdir is a temporary working directory provided to the program as a servlet parameter.
Validate true whether to use the new format configuration file
Vallidating true: whether to analyze the validity of the configuration file
In most cases, standard servlets can meet user needs.
When the URI of a specific request is received for the first time, actionservlet instantiates the appropriate action class and stores a reference in the action class instance with the servlet variable name. After being instantiated, the action class will be saved for future use.
Actionservlet also provides some methods for the action class to access resources such as data sources and forwarding targets.
Actionservlet Method
Actinservlet provides a set of methods that can be used by action objects.
All information about struts APIs can be found in the struts-documentation.war. Dynamic addition or deletion. These methods only affect the current instance of the application:
Public void addformbean (actionformbean formbean)
Public void removeformbean (actionformbean formbean)
Public void addforward (actionforward)
Public void removeforward (actionforward)
Public void addmapping (actionmapping)
Public void removemapping (actionmapping)
Search for objects by name:
Public actionformbean findformbean (string name)
Public actionforward findforward (string name)
Public actionmapping findmapping (string name)
Used to process data sources:
Public void adddatasource (string key, datasource DS)
Public datasource finddatasource (string key)
We can also:
Use the destroy () method to end actionservlet
Use the reload () method to reload information from the struts configuration file.

3.3 actionmapping class
Maps specific requests to specific actions and stores the information in actionmapping. actionservelt transfers actionmapping to the perform () method of the action class. Action uses the findforward () method of actionmapping, this method returns an actionforward with the specified name, so that the action completes local forwarding. If no specific actionforward is found, a null value is returned.
Public actionforward findforward (string name)
You can dynamically add actionforward in the ing:
Public void addforward (actionforward forward)
You can return the form bean associated with the ing:
Public String getname ()
Returns the mapped property domain (session or request)
Public String getscope ()

3.4 action class
The action class truly implements the transaction logic of the application, and they are responsible for processing requests. After receiving the request, actionservlet will:
Select the appropriate action for this request
If necessary, create an instance of action
Call the perform () method of action
If the actionservlet cannot find a valid ing, it will call the default action class (defined in the configuration file ). If the actionservlet is found to forward the appropriate actionmapping class to the action, this action uses actionmapping to locate the local forwarding, and then obtains and sets the actionmapping attribute. Based on the servlet environment and the signature of the overwritten perform () method, actionservlet also transmits the servletrequest object or httpservletrequest object.
All action classes are extended to the org. Apache. Struts. action. Action class, and override a perform () method defined in the class. There are two perform () methods:
Process non-HTTP (general) Requests:
Public actionforward perform (actionmapping action,
Acionform form,
Servletrequest request,
Servletresponse response)
Throws ioexception, servletexception
Process HTTP requests:
Public actionforward perform (actionmapping action,
Acionform form,
Httpservletrequest request,
Httpservletresponse response)
Throws ioexception, servletexception
The action class must be programmed in the "thread-safe" way, because the Controller will share multiple concurrent requests to the same instance. When designing the action class, pay attention to the following points:
You cannot use instances or static variables to store the status information of a specific request. They share the global resources that span the request in the same operation.
If the resources to be accessed (such as JavaBean and session variables) need to be protected during parallel access, the access must be synchronized.
Action Class Method
In addition to the perform () method, the following methods are available:
You can obtain or set the region associated with the request:
Public locale getlocale (httpservletrequest request)
Public void setlocale (httpservletrequest request, locale)
Obtain Message Resources for applications:
Public messageresources getresources ()
Check whether the user clicks the "cancel" key on the form. If yes, true is returned:
Public Boolean iscancelled (httpservletrequest request)
When an application error occurs, the action class can use the following method to store the error message:
Public void saveerrors (httpservletrequest request, actionerrors errors)
The actionerror instance is used to store error information. This method stores the actionerror object in the request attribute list under the error keyword. By using the custom tag defined in the struts tag library, the JSP page displays these error messages, which will be described later.

3.5 actionform class
The framework assumes that the user creates an actionform bean for each form in the application, for each bean defined in the struts-config.xml file, the Framework calls the perform () of the Action class () before using this method, perform the following operations:
Under the associated keyword, it checks the user session used for the bean instance of the appropriate class. If no bean is available in the session, it automatically creates a new bean and adds it to the user's session.
For each parameter in the request that corresponds to the bean property name, Action calls the corresponding setting method.
When action perform () is called, the latest actionform bean is sent to it, and the parameter value can be used immediately.
Extended Org. apache. struts. action. actionform class, the bean created by the program developer can contain additional attributes, and the actionservlet may use reflection (allow retrieving information from loaded objects) to access it.
The actionform class provides another way to handle errors. It provides two methods:
Public actionerrors validate (actionmappin mapping,
Servletrequest request)
Public actionerrors validate (actionmappin mapping,
Httpservletrequest request)
You should overwrite the validate () method in your bean and set the validate of the <action> element to true in the configuration file. Before the actionservlet calls the action class, it calls validate (). If the returned actionerrors is not null, actinform stores actionerrors in the request attribute list based on the error keyword.
If the returned value is not null and the length is greater than 0, the instance is stored in the request attribute list based on the error keyword, then, actionservlet forwards the response to the target pointed to by the INPUT attribute of the <action> element in the configuration file.
If you need to perform a specific data validity check, it is best to perform this operation in the action class instead of in the actionform class.
Method reset () to restore bean attributes to the default value:
Public void reset (actionmapping mapping, httpservletrequest request)
Public void reset (actionmapping mapping, servletrequest request)
A typical actionfrom bean only has the attribute setting and reading method (getxxx), but does not implement the transaction logic. Only the simple input check logic is used to store the latest data entered by the user in the relevant form, so that the same web page can be regenerated and a set of error messages are provided, in this way, users can modify incorrect input data. The actual check on the Data validity is the action class or the appropriate transaction logic bean.

3.6 actionforward class
The objective is to forward the processing results of the action class to the destination.
The action class obtains the handle of the actionforward instance and can return to the actionservlet using three methods, so we can use findforward () as follows ():
Actionservlet obtains a Global Forwarding rule by name.
The actionmappin instance is transferred to the perform () method, and a local Forwarding is found based on the name.
The other is to call the following constructor to create their own instance:
Public actionforward ()
Public actionforward (string path)
Public actionforward (string path, Boolean redirect)

3.7 handle errors
Struts provides two classes to handle errors: actionerrors and actionerror. They both extend org. Apache. Struts. Action. Actionerrors stores a set of actionerror objects, each of which represents an independent error message. Each actionerror contains a keyword that can be mapped to the error information stored in the resource file, which is specified in the actionservlet initialization parameter.
Actionerror class
The actionerror class defines a set of overloaded constructors to create error messages. The first constructor method uses a string as a parameter, for example:
Actionerror error = new actionerror ("error. invalid ");
An error message mapped from instance error to Application resource file:
Error. Invalid = <B> invalid number </B>
If you use <HTML: Error> On the JSP page, you will see the bold invalid number.
Another type uses the java. Text. messageformat class. You can specify the replacement string in the message, for example:
Error. Invalid = <B> invalid number </B>
Create an error message:
Actionerror error = new actionerror ('error. invalid', new double (-1 ));
JSP page: invalild number-1
There are also error keywords for getting specific messages:
Public String getkey ()
You can also obtain the replacement string array:
Public String [] getvalues ()

Actionerror class
The actionerror class never handles errors independently. They are always stored in the actionerrors object. The actionerrors object stores the set of actionerror classes and their specific attribute values. We can use our own defined attribute values or use actionerrors. global_error.
The following describes how to handle errors in a typical action class perform:
Myform form = (myform) form;
If (number =-1 ){
Actionerrors errors = new actionerrors ();
Actionerror error = new actionerror ("error. invalid", New Double (-1 ));
Errors. Add (actionerrors. global_error, error );
Saveerrors (req, errors );
String input = mapping. getinput ();
Return new actionforward (input );
}
Actionerrors provides the following useful methods:
Method description
Clear () Clear all error messages
Empty () if the actionerrors object is empty, it returns true
Get () returns an error message. If no parameter exists, all information is returned as an iterator object.
Properties () returns the iterator containing the property name, which has at least one error
Size () number of returned errors (integer)

There is also a more powerful architecture developed based on struts.
These plug-ins with excellent functions can be found in eclipse development.
A great deal of "Dummies"
But it will be difficult to understand.
Easy to understand and develop

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.