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:
1. Control the class of the program process
2. Classes to implement and implement procedures transaction logic
3. Customized tag library makes it easier to create and verify the HTML form.
1.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:
Document 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 with all Java classes in the Struts. Also need to be copied to web-inf / lib * .tld tag library descriptor file, describe 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-documentation.war contains all Struts Documents Struts-Example.war strut Struts-Example.War Struts Struts-EXERCISETAGLIB.WAR is mainly used to customize label libraries Increase and use the test page, but you can also demonstrate how to use the struts tag Struts-Template.war contains a simple example of the Struts template tag. Struts-upload.war is a simple example of how to use the struts framework to upload files.
1.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.
1.2.1 model
In the Struts framework, the model is divided into two parts:
Internal state of the system
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.
1.2.2 Window
Established by JSP, Struts contains extended custom label libraries to simplify the process of created a fully international user interface.
1.2.3 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.
2
1.3 components in the Struts framework
(Because the ROSE tool has not been downloaded, only this picture, it illustrates a certain problem, especially ActionerRors, but it does not use the ActionMApping, JSP, and Tag Library, and have a time-finished replacement) framework. Components used:
ActionServlet Controller ActionClass Contains Transaction Logic ActionForm Display Module Data ActionMApping Help Controller to Map to ActionForward Use to indicate Observed Object ActionError Used to Storage and Recycling Error The Struts Tag Library can reduce the development display hierarchy
Let's take a look at the roles and responsibilities they play in the framework.
1.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:
Global forwarding
ActionMApping class
Actionform Bean
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)
3
global-forwards>
Property Description Name Global Forwarded Name Path Path and 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. E.g:
TYPE = "BOOKACTION" Name = "BOOKFORM" Scope = "request" INPUT = "/ createbook.jsp"> action> action-mappings> Property Description The relative path of the PATH Action class NAME is connected to the Action BEAN of the Action BEAN Type connected to the Action of the Action Class of this map (can be included) Scope ActionForm Bean scope (request or session) prefix is used to match the request The prefix of the parameter and the bean property is used to match the suffix attribute scope of the request parameter to the bean property. The fully qualified name of the class of the classname actionMapping object is org.apache.struts.Action.ActionMapping input input to the path to enter the form, pointing to the Control Unknown, which must return to the BEAN, set to True, the operation will be used as all unselected The default operation of the ActionMapping URI is set to TRUE, before calling the Perform () method on the Action object, the ActionServlet will call an actionform bean's validate () method for input check via Property Description ID ClassName ActionForWard class fully qualified name, default is org.apache.struts.Action.ActionForwardName Operation class Access ActionForward's logical name path response forwarded target resource path 4 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> Property Description ID ClassName ActionForm Bean's fully qualified name, the default value is the name of the org.apache.struts.Action.ActionFormBean Name form BEAN in the relevant scope, this property is used to associate bean with actionmapping's fully qualified name of the TYPE class Configure JDBC data sources Use the Property Description ID The Id KEY Action class uses this name to find the name of the class that connects Type to implement 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> Property Description Description Data Source Description AutoCommit Data Source Create The default automatic update number used by the connection 5 According to the class used by the library mode DriverClass data source, it is used to display the limit of the JDBC driver interface logintimeout database login time. In seconds, the maximum number of connections that MAXCOUNT can be created by mincount, the minimum number of connections to create, the password, the password, the password, readonly created Read-only User Access Database URL of URL JDBC 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 (); 1.4 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 feature is: 1. Intercepting the user's HTTP request 2. Map this 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 Beans, Action Mapping objects, Request Pass with the Response object. Such as: Public ActionForWord Perform (ActionMapping Mapping, ActionForm, httpservletRequest Request, HttpservletResponse response) 5.Perform Returns an ActionForWord object, which is connected to the appropriate JSP page. 1.4.1 ActionServlet configuration We need to declare an actionServlet in Web.xml and configure it to be loaded. The initialization parameters that can be configured below: Parameter Default Value Description Application Null Application Resource Collection Class Buffersize 4096 file upload buffer size 6 CONFIG /WEB-INF /STRUTS-CONFIG.XML Position and Name Content Text / HTML Default Content Type Debug 0 Program Debug Level Detail 0 Program Debug Detail level Factory Null Message Resource Factory, used in internationalization Message Resources FORMBEAN Org.Apache.Struts.Action.ActionFormBean Package Actionform Bean Information Class of the class forward org.apache.struts.Action.ActionForward package ActionForward object information The name locale true True will store one in the user session ActionMapping local object mapping org.apache.struts.action.ActionForward package name of the class information maxFileSize maximum size multipartClass org.apache.struts.action.ActionForward 250M uploaded file handle name noCache False HTTP header like multi-part request whether To set to a disabled rue set to True, return null tempdir as a servlet parameter to the program to use the temporary work directory Validate TRUE to use the new format Vallidating TRUE Whether to analyze the configuration files 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. 1.4.2 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) Seduce 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: End ActionServlet using the destroy () method Use the Reload () method to reload the information from the Struts profile. 1.5 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 don't find the specific ACTIONFORWARD, 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 () 1.6 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: Select the appropriate action for this request Create an instance of an action if needed Call an action 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: 8 Public ActionForward Perform (ActionMapping Action, ACIONFORM FORM, ServletRequest Request, ServletResponse response) THROWS IOEXCEPTION, ServletException Handle HTTP request: 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: 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. If you want to access resources (such as JavaBean and Session Variables) need to be protected when parallel access, then access to synchronize 1.6.1 method of the 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) Gets Message Resources for the 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. 1.7 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: Under the associated keyword, it checks the user session for a 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. For each parameter corresponding to the bean property name, the Action calls the corresponding setting method. 9 When Action Perform () is called, the latest ActionForm bean is delivered 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) Typical ActionFrom Bean is only available for the settings and reading methods (Getxxx) without implementing 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. 1.8 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 (): ActionServlet obtains a global forwarding according to the name ActionMAppin instance is transmitted to the Perform () method, and find 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) 10 1.9 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. 1.9.1 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 Another Java.Text.MessageFormat class can specify a replacement string in the message, for example: 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 () 1.9.2 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 a 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: 11 Method Description clear () Clear all error messages EMPTY () If the ActionerrorS object is empty, it returns true get () returns an error message. If there is no parameters, all information will return Properties as an Iterator object () Returns the item containing the name of the property name, these attributes have at least one error size () returns the number of errors (intensity)