table of Contents
sequence
…………………………………………………………………………………………………1
table of Contents
…………………………………………………………………………………………………2
Struts framework
1. Struts compression package content .........................................................................
2. Struts Architecture (Model - Window - Controller) .....................................................
3. Struts framework components ......................................................................... 4
3.1 Struts configuration file ........................................................................ 5
3.2 ActionServlet class ........................................................................ 7
3.3 Actionmapping Class ........................................................................ 9
3.4 Action class ...............................................................................
3.5 Actionform class ......................................................................... 10
3.6 ActionForward class ...................................................................................
3.7 Error handling .....................................................................................................
Struts framework
The Struts framework has the advantages of module, flexibility, and reuse of the components, and simplifies the development of MVC-based web applications.
This chapter discusses the Struts architecture in detail. We will see how Struts clearly define control, transaction logic, and appearance, simplifying the development of application processes. We will also introduce how the class provided by Struts makes development work more simple, including:
l Control the program process
l Classs that implement and execute program transaction logic
l The custom tag library makes it easier to create and verify the HTML form.
1. Struts compressed package content
Folder Jakarta-Struts-1.0.2 contains two directories, libs, and webapps. In the lib directory, you can use Struts to create an application is the required file:
file
description
JDBC2_0-stdext.jar
Contains a JDBC2.0 Optional Package API class. If we want to use the data resources provided by Struts, you 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
* .tld
The tag library descriptor file describes custom tags in multiple Struts tag libraries. Also copy to Web-Inf / Lib
There is a file under the WebApps directory:
Web application
description
Struts-blank.war
A simple web application
Struts-docuumentation.war
Contains all Struts documents on the Struts site
Struts-esample.war
Struts a lot of features demonstration
Struts-EXERCISETAGLIB.WAR
Mainly used to increase the test page for custom label libraries, but can also demonstrate how to use Struts tags
Struts-template.war
Introduction and examples of Struts template tags
Struts-upload.war
A simple example, demonstrate how to use the struts framework upload file
2.Struts architecture
Let us observe the components in the Struts frame from the angle of the MVC
Three parts of the frame: model, window and controller.
model
In the Struts framework, the model is divided into two parts:
l system internal state
l You can change the status of the status (transaction logic)
The internal state is usually represented by a set of ActInform JavaBean. These beans may be self-contained and have a continuous state depending on the design or application complexity, or data (from a database) is only available when needed. Large applications are typically encapsulated transaction logic (operation) in method, which can be called the bean call. For example, shopping cart bean, it has information about purchasing goods, there may be a checkout () method to check the user's credit card, and send information to the warehouse.
In a small program, the operation may be embedded in the Action class, which is part of the controller role in the Struts framework. This method is very suitable when logic is simple.
It is recommended that users separate transaction logic (what to do) with the role (decision to do) played by the Action class.
Windows
Established by JSP, Struts contains extended custom label libraries to simplify the process of created a fully international user interface.
Controller
In Struts, the basic controller component is an instance servert in the ActionServlet class, and the actually used servlet is defined by a set 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, only this picture can be found, it illustrates a certain problem, especially ActionerRors, but it does not contain ActionMapping, JSP, and Tag Library, there is time to replace it.)
The components used in the frame:
ACTIONSERVLET
Controller
ActionClass
Contains transaction logic
Actionform
Display module data
ActionMapping
Help the controller to map the request to the action
ActionForward
Objects used to indicate operational transfer
Actionerror
Used to store and recycle errors
Struts tag library
Can reduce the development of development display hierarchy
Let's take a look at the roles and responsibilities they play in the framework.
3.1 Struts Profile
This is the strew-config.xml that combines the Struts component: struts-config.xml. Defaults
/Web-inf/struts-config.xml. Profiles can be defined:
l Global forward
l actionmapping class
l actionform bean
l JDBC data source
Configure global forwarding
Global forwarding is used to create logical name mappings between JSP pages. Forwarding can be obtained by an instance that calls an operation map, for example:
ActionMappingInstace.FindForward ("LogicalName");
Example of global forwarding: (All example I have not explained, one is that the combination table can be understood, the second is that most of the examples from the series four, you should take a look after the experiment, then look at it)
global-forwards>
Attributes
description
Name
Global forwarded name
Path
Relative path with target URL
Configuring actionmapping
The ActionMapping object helps process control within the framework, which can map 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 an instance of a specific Action class. All Action classes use the Perform () method to implement a specific application code, return an ActionForward object, including the target resource name of the response forwarding. For example:
TYPE = "BOOKACTION" Name = "BOOKFORM" Scope = "request" INPUT = "/ createbook.jsp"> action> action-mappings> Attributes description Path The relative path of the Action class Name The name of the action bean associated with this operation Type Connect to the full name of the Action class (available) Scope Actionform bean scope (request or session) Prefix Used to match the prefix of request parameters and bean properties SUFFIX The suffix used to match the request parameters and the bean property Attribute Scope domain name. Classname The fully qualified name of the class of the ActionMapping object is org.apache.struts.Action.ActionMapping INPUT Enter the path to the form, pointing to the control of the input error that occurs in the bean. Unknown Set to True, the operation will be used as the default operation as all the URIs that are not defined. Validate Set to True, before calling the Perform () method on the Action object, the ActionServlet will call the validate () method of the ACTIONFORM BEAN for input check. With Attributes description Id Id Classname The fully qualified name of the ActionForward class, the default is org.apache.struts.Action.ActionForward Name The logical name used when operating the class access ActionForward Path Path to respond to forward target resources REDIRECT If set to True, ActionServlet uses the sendredirect () method to forward resources. Configuring an actionform bean The ActionServlet uses ActionForm to save the request parameters, these beans correspond to the name in the HTTP request parameter, the controller passes the request parameters to the ActionForm bean instance, and then transfer this instance to the Action class. example: form-beans> Attributes description Id Id Classname The fully qualified name of the Actionform bean, the default value is org.apache.struts.Action.ActionformBeanName The form bean is in the name of the related scope, this property is used to associate bean with actionmapping Type Quick qualification name Configure JDBC data sources Use the Attributes description Id Id Key Action class uses this name to find a connection Type The name of the class that implements the JDBC interface The following property requires the Key = "contool" TYPE = "org.apache.struts.util.GenericDataSource" AutoCommit = "True" Description = "EXAMPLE DATA SOLRE Configuration" Driverclass = "org.test.mm.mysql.driver" Maxcount = "4" MinCount = "2" URL = "JDBC: mysql: // localhost / test" User = "struts" Password = "wrox" /> data-sources> Attributes description DESCIPTION Description of data sources AutoCommit The default automatic update database mode used by the connection created by the data source Driverclass The class used by the data source is used to display the JDBC driver interface. Logintimeout Database login time limit, in seconds Maxcount Up to most established connections minCount Minimum number of connections to create Password Database Access password Readonly Create a read-only connection User Access the user name of the database URL JDBC URL By specifying the keyword name, the Action class can access the data source, such as: Javax.sql.datasource DS = servlet.finddataSource ("contool"); Javax.sql.connection con = ds.getConnection (); 3.2 ActionServlet class The controller component in the frame is an org.apache.struts.Action.ActionServlet class implementation, this class is an extension of the javax.servlet.http.httpservlet class. The Struts Controller's basic function is: 1. Intercepting the user's HTTP request 2. Map the request to the corresponding Action class, if this is the first request received by this class, the instance will be initialized Capacity. 3. Create or discover an ActionForm bean instance (see if the configuration file is defined), then transplant the request process to Bean.4. Call the perform () method of the Action instance and use Actioform Bean, Action Mapping object, Request Pass with the Response object. For example: public actionforword perform, httpservletRequest request, httpservletRequest request, httpservletResponse response 5.Perform returns an actionForWord object, this object is connected to the corresponding JSP page .ActionServlet configuration We need to declare an actionServlet in Web.xml and configure it to be loaded. The following is an initialization parameter that can be configured: parameter Defaults description Application NULL Class for the resource collection of the app Buffersize 4096 File upload buffer size Config /Web-inf/struts-config.xml Profile location and name Content Text / html Default content type Debug 0 Program debugging level Detail 0 Level of procedures debugging details Factory NULL Message resource factory, used in internationalization interpretation of news resources FORMBEAN Org.apache.struts.Action.Actionformbean Name of the class of encapsulation Actionform bean information Forward Org.apache.struts.Action.ActionForward The name of the class of encapsulating an actionforward object information Locale True For True, a local object will be stored in the user session mapping Org.apache.struts.Action.ActionForward Name of the class of encapsulation activitymapping information MaxFilesize 250M Uploaded the maximum size of the file MultipartClass Org.apache.struts.Action.ActionForward Treat a name of the class that handles multiple pieces Nocache False Does the HTTP header want to set to disabled? NULL True Set to True, return null for invalid information keywords Tempdir A work directory for the program as a servlet parameter Processing download files is a temporary work directory for use Validate True Whether to use a new format profile Vallidating True Whether to effectively analyze the configuration file In most cases, the standard servlet can meet the needs of users. When the URI of the first received a specific request, the ActionServlet instantiates the appropriate Action class, and the ActionServlet stores a reference in servlet in the Action class instance. When instantiated, the Action class will be temporarily stored. ActionServlet also provides some methods that use the Action class to access resources such as data sources and forwarding targets. ACTIONSERVLET method ActinServlets provide a group of methods that can be used by Action objects. All information for the Struts API can be found in Struts-Documentation.war. Dynamic add or delete, these methods only affect the current instance of the application: Public Void AddFormbean (ActionformBean Formbean) Public Void RemoveFormBean (ActionformBean Formbean) Public Void Addforward (ActionForward ActionForward) Public Void RemoveForward (ActionForward ActionForward) Public Void AddmApping (ActionMApping ActionMApping) Public void removemapping (actionMapping actionmapping) Find objects according to the name: Public ActionFormBean FindFormbean (String Name) Public ActionForward FindForward (String Name) Public anctionMAPPING FINDMAPPING (String Name) Used to process data sources: Public Void AddDataSource (String Key, DataSource DS) Public DataSource FindataSource (String Key) We can also: l End an ActionServlet using the destroy () method l Use the reload () method to reload the information from the Struts profile. 3.3 ActionMApping class The relevant information mapped to a specific Action is stored in an actionMApping. ActionServelt transmits actionMApping to the Perform () method of the ActionMApping, Action will use an actionMApping's FindForward () method, this method returns an actionforward that specifies the name, so that ACTION Completed local forwarding. If you do not find a specific ACTIONFORWARD, you will return a NULL. Public ActionForward FindForward (String Name) You can dynamically add ACTIONFORWARD in the mapping: Public Void Addforward (ActionForward Forward) You can return to form beans associated with mapping: Public string getName () Remove the mapping attribute domain (session or request) Public string getscope () 3.4 Action class The Action class truly implements the application's transaction logic, which is responsible for processing the request. After receiving the request, the ActionServlet will: l Select the appropriate action for this request. l If you need, create an instance of an action l Call an perform () method If an ActionServlet does not find a valid map, it calls the default Action class (defined in the configuration file). If you find the ActionServlet forward to the appropriate actionMApping class, this action uses actionMapping to find local forwarding, then get an actionMApping property. The ActionServlet also transmits the ServletRequest object or HTTPServletRequest object according to the signature of the servlet environment and the overform () method. All Action classes expand the org.apache.struts.Action.Action class, and override a perform () method defined in the class. There are two perform () methods: Handling non-HTTP (general) request: Public ActionForward Perform (ActionMapping Action, ACIONFORM FORM, ServletRequest Request, ServletResponse response) THROWS IOEXCEPTION, ServletException handles HTTP requests: Public ActionForward Perform (ActionMapping Action, ACIONFORM FORM, HTTPSERVLETREQUEST REQUEST, Httpservletresponse response THROWS IOEXCEPTION, ServletException The Action class must program as "thread security" because the controller will share the plural simultaneous request to share the same instance, according to the design of the Action class, you need to pay attention to the following points: l You cannot use instances or static variables to store status information for specific requests, which share global resources across the request in the same operation. l If the resources you want to access (such as JavaBean and Session Variables) need to be protected when parallel access, then access is synchronous Method of Action class In addition to the perform () method, there is also the following methods: You can get or set the area associated with the request: Public Locale getLocale (httpservletRequest request) Public void setlocale (HttpservletRequest Request, Locale Locale) Get a message resource for your application: Public MessageResources getResources () Check if the user clicks on the "Cancel" button on the form, if yes, True will be returned: Public Boolean ISCANCELED (HTTPSERVLETREQUEST REQUEST) When an application error occurs, the Action class can store error messages using the following method: Public Void SaveErrors (HttpservletRequest Request, ActionerRors Error) The ActionError instance is used to store an error message, which stores the ActionError object in the request attribute list under the error key. The JSP page can display these error messages by using the custom tag defined in the Struts tag library. We will introduce later. 3.5 Actionform class The framery assumes that the user creates an actionform bean for each form in the application, and the framework will do the following before the bean defined in the Struts-Config.xml file is called before the action class: l In the associated keyword, it checks the user session of the Bean instance for the appropriate class, if there is no Bean available in the session, it will automatically create a new bean and add it to the user's session. l For each parameter corresponding to the bean property name, the Action calls the corresponding setting method. l When Action Perform () is called, the latest ActionForm bean is transmitted to it, and the parameter value can be used immediately. ActionForm class extension org.apache.struts.Action.Actionform class, the BEAN created by program developers can include additional properties, and ActionServlet may use reflection (allowing recycling information from loaded objects) to access it. The ActionForm class provides another means of handling errors, providing two methods: Public ActionerRors Validate (ActionMappin Mapping, ServletRequest request) Public ActionerRors Validate (ActionMappin Mapping, HTTPSERVLETREQUEST REQUEST) You should override the validate () method in your own bean, and set the validate of the If the returned is not NULL, and the length is greater than 0, the instance is stored in the requested attribute list according to the error key, and then the ActionServlet will be forwarded to the target pointing to the INPUT property of the configuration file If you need to perform a specific data validity check, it is best to do this in the Action class, not in the ActionForm class. Method RESET () can restore the properties of the bean to the default value: Public void reset (actionMapping mapping, httpservletRequest request) Public Void Reset (ActionMapping Mapping, ServletRequest Request) A typical actionFrom bean only has a method of setting with a read method (Getxxx) without transaction logic. Only simple input check logic, the purpose of use is to store the latest data entered in the relevant form so that the same web page can be regenerated while providing a set of error messages so that the user can modify the incorrect input data. It is really checking data validity to check the Action class or the appropriate transaction logic bean. 3.6 ActionForward class The purpose is to forward the processing results of the Action class to the destination. The Action class gets the handle of the ActionForward instance, and then use three methods to return to the ActionServlet, so we can use Findforward (): l ActionServlet obtains a global forwarding according to the name l ActionMAppin instance is transmitted to the Perform () method, and found a local forwarding according to the name The other is to call the following constructor to create an example of themselves: Public anctionforward () Public ActionForward (String Path) Public ActionForward (String Path, Boolean Redirect) 3.7 Error handling Struts provides two classes to handle errors: ActionerRRORS and ActionError, they all expand org.apache.struts.Action. ActionerRORS saves a collection of ActionError objects, each represents an independent error message. Each ActionError contains a keyword, which is mapped to the error message stored in the resource file, and this resource file is specified in the ActionServlet initialization parameter. ActionError class The ActionError class defines a set of overloaded constructors to create an error message, the first constructor method uses a string as a parameter, for example: Actionerror Error = New Actionerror ("Error.INvalid"); Example Error maps an error message in the application resource file: Error.INValid = invalid number b> If you use Error.invalid = invalid number {0} b> Create an error message: ActionError Error = New Actionerror ('Error.invalid', New Double (-1)); JSP page display: Invalild Number -1 There is also a wrong keyword for a specific message: Public string getKey () There is also an array of replacement strings: Public String [] getValues () ActionError class The ActionError class is not independently errors, which are always stored in the ActionerRors object. The ActionerRors object saves a collection of ActionError classes and their specific attribute values, we can use your own defined attribute value, or use ActionerRors.global_ERROR. Below is an error handling in Perform () of the typical Action class: MyForm Form = (MyForm) Form; IF (Number == -1) { ActionerroS Errors = new actionerrors (); ActionError Error = New ActionError ("Error.INvalid", New Double (-1)); Errors.Add (ActionerRors.global_Error, Error); SaveerRors (Req, Errors); String infut = mapping.getinput (); Return New ActionForward (Input); } ActionerRors have the following useful methods: method description Clear () Clear all error messages EMPTY () If the ActionerRors object is empty, it returns true Get () Returns the error message. If there is no parameters, all information will be returned as an Iterator object. Properties () Returns the Iterator containing the name of the property, these attributes have at least one error Size () Returns the number of errors (integer)