Part 1: Introduction Struts started in March 2000, is a framework for developing an open source of web applications using Java Servlet / JavaServer Pages technology.
The Struts can develop Java web front-end applications based on MODEL-View-Controller design mode. Usually the MVC design pattern divides a system into three parts: mutual collaboration:
1, Model, model for packaging system, such as business data;
2, View, the view is the representation of the model, providing the user interaction interface. When the model state changes, the view should be notified to update the change in the model;
3, Controller, accept the request from the view, modify the status of the model.
The Struts application has 3 main components: one is the central controller implemented using the servlet (Controller Servlet, the org.apache.Action. ActionServlet class provided by Struts) and an action responsible for the specific business logic processing (org.apache.action. The subclass of Action); one is a JSP page for display; the other is a business logic element (model) for encapsulating system status. The center controller of the Struts accepts all requests from the client and routes the HTTP request to other Action objects (subclasses of the developer implementation) based on the system's configuration (Struts-Config.xml). All business operations are completed in these Action objects, such as inserting a order, modify a record, etc. After processing, the struts' controller servlet is turned to the appropriate JSP page according to the configuration, and the processing result is displayed to the user. As you can see here, the Controller Servlet in Struts has a significant role that controls all the program flows, allowing the three of the three relatively independent partial coordination to make the system more perfect.
Part II: System Environment and Installation Version
1, system environment
Operating system: Windows XP SP1
Web server: Tomcat
5.0.14
2, Struts version
This article uses Jakarta-Struts-20031118 version (subordinate version 1.1 version series), download address:
http://jakarta.apache.org/builds/jakarta-struts/release/
We get the installation package JAKARTA-STRUTS-20031118.ZIP.
Part III: Installation Configuration Struts
1, install struts
Unzip JAKARTA-STRUTS-20031118.ZIP package to E: / MyLib / Jakarta-Struts. It includes two subdirectorys with lib and webapps. In the lib subdirectory, the JAR file required for Struts, the label default file (.TLD), and the DTD definition (.dtd) for web.xml and struts-config.xml configuration files for a Struts web application. The WebApps subdirectory contains several Struts sample applications, which have been packaged as .war format, here mainly three of them:
1. Struts-Example.war, a simple sample program for Struts framework Controller; 2. WAR package for Struts-documentation.war, Struts document;
3. Struts-Blank.war, a blank Struts application, can be easily modified, and configure your own application.
If we want to build a new app, we will use the third as a basic framework.
2, run struts-example.war
Turn struts-esample.war to the WebApps directory under Tomcat. Then start Tomcat, Tomcat automatically extracts the War package when starting (if there is no automatic decompression, check if your Tomcat server is formulated into the mode directly running the WAR document), enters http: // localhost: 8080 in the browser / struts-example, if you can see the page shown below, you have run successfully.
In the figure above, you can click "Register With The Mailreader Demonstration Application" to register a MailReader user, or click on "Log On to the Mailreader Demonstration Application", enter the username and password (the sample program has preset a user / pass, Configure the web-inf / database.xml file under Struts-Example).
3. Analysis of routines
(1) Web.xml analysis
In the page shown in the figure above, click on the "Log On to the Mailreader Demonstration Application" link, enter the /logon.jsp page, enter the predefined username User, password is Pass, then submit it into the picture below The home page of the user.
Note that the suffix of the URL here is .do. So what is it meaningful? How is the server handles such a request? Look at the {Tomcat} /web-inf/web.xml file, it will be very clear. In Web.xml, you can find the following configuration segment:
servlet-maping>
From the above configuration code, you can know that the request URL ending at .do is processed by a servlet called Action. It can actually take another suffix to apply, as long as you modify it here.
Look at the following configuration summary:
Org.apache.struts.Webapp.Example.ApplicationResources
param-value>
init-param>
init-param>
......
servlet>
It can be seen that the class corresponding to the Action is org.apache.struts.Action.ActionServlet. This is a Struts provided by the center-control position servlet, which is a CONTROLLER Servlet, which is used to listen to all requests from the user from the user. DO suffix. In the above configuration, an initialization parameter named config is configured for the ActionServlet, the value of /Web-inf/Struts-Config.xml. Struts-config.xml is an important configuration file based on Struts application, which contains all Action requests (referring to requests ending with .do), corresponding ACTION processing classes, form beans, and pages. Configuration. Struts-config.xml is read when the application is started and then responds based on these configurations. The following is an example of the configuration of the logonaction in the sample program, and analyzes Struts-Config.xml.
(2) Struts-config.xml analysis
Below is some code for configuring the logonaction in struts-config.xml:
Path = "/ logon" Type = "org.apache.struts.Webapp.Example.logonaction" Name = "logonform" Scope = "request" INPUT = "/ logon.jsp"> action> As can be seen from the above, the request for /logon.do in the MailReader application is processed by the org.apache.struts.WebApp.example. The Name property specifies the model component corresponding to the corresponding form corresponding to the request. LogonForm is also configured in struts-config.xml, below is part of its configuration: Type = "org.apache.struts.validator.dynavalidatorform"> form-bean> The LogonForm class is a normal JavaBean, which defines several properties and properties read and write methods, and the names of these properties are corresponding to the input domains in the page form. For example, two properties are defined in the logonform, the code is as follows: Private string username = null; Private string password = null; These two attributes correspond to two input domains in the Logon.jsp form, respectively, the code is as follows: Here you should pay attention to a point, the attribute name in the logonform must be completely corresponding to the single domain name in Logon.jsp. Struts is here to grab the submitted data from the browser side, and fill it into the LogonForm object, and then transfer to the LogonAction class for processing. The form verification and reset technology implemented by Struts is also achieved. In the page code above, we used Struts's HTML custom label libraries, which defined in the Struts label library, and you can find it, but it is recommended that everyone is best to use, because these labels support JavaScript events are very Less, and lost the support of automatic backfill, so it is better to do itself. You can also use the HTML code similar to to find it in the label library of Struts. (3) Action analysis Above we have had a certain understanding of the overall structure of the Struts front-end application framework. I also know how Struts get configuration information from the configuration file, that is, start, then wait for the request, then grab the data from the front desk, call (or generate) the Action class according to the configuration information, and finally steady depending on the results of the processing The corresponding page responds to the user. Then, let's see how LogonActions is working on business processing and display the processing results to users. The main code is as follows: Package org.apache.struts.Webapp.Example; Import org.apache.struts.Action.action; ...... Public Final Class LogonAction Extends Action { Public ActionForward Perform (ActionMapping Mapping, Actionform Form, HTTPSERVLETREQUEST REQUEST, Httpservletresponse response THROWS IOException, servletexception { ...... ActionerroS Errors = new actionerrors (); String username = ((logonform) form .getusername (); String password = ((logonform) form .Getpassword (); ...... // Perform user verification // If there is no such user, or the password is incorrect, add an error to ErrorS. IF (! errors.empty ()) { SaveerRors (Request, Errors); Return (maping.getInput ()))); } HttpSession session = request.getations (); Session.SetaTRibute (constants.user_key, user); / / Delete expired Form Bean ...... IF (mapping.getattribute ()! = null) { IF ("REQUEST" .Equals (mapping.getscope ())))) Request.Removettribute (mapping.getattribute ()); ElSesession.RemoveAttribute (mapping.getattribute ()); } / / Position to success page Mapping.Findforward ("Success")); } } } The LogonAction class inherits in org.apache.struts.Action.Action, the Action class is the base class of all Action. The PerForm () method defined is done the request processing, and turns to a different page based on the processing result, and then displayed to the user. The Action class is not a servlet, which does not directly monitor requests from the client. The center controller ActionServlet mentioned above is a servlet, the Action request sent by the client, received by the ActionServlet, according to the configuration in Struts-Config.xml, incoming the corresponding mapping, form, request, response object, and call the corresponding The perform () method of the Action class is processed (instantiated an action during the first call, and the subsequent request will directly call the existing Action class for processing, so the Action class is shared, and the programming should pay attention to handling concurrency problem). The following is a simple analysis of the Perform () method of the above LogonAction. 1. First get UserName and Password from the incoming Form object. When do we strange these two attributes when is it placed? This is an ActionServlet requests to capture data from the date of the Logonform object based on the configuration in Struts-Config.xml before calling the LogonAction's Perform () method. Then use user authentication. This example does not use the database to store, the user information is stored in the Database.xml file. If UserName / Password does not exist or password errors in the database.xml file, generate an ActionError object, store the error message into the object, and add this object to the ActionerRORS, and other errors are similar processing. In the subsequent program, the first school check has an error. If there is an error, the error object is stored in the request, and the method used is SaveerRors (Request, Errors). The method is implemented in base class org.apache.struts.action.Action, which is easy to complete, and store the ErrorS object to the request through the setAttribute () method. The implementation is as follows: Protected Void SaveErrors (httpservletRequest Request, ActionerrorS Errors) { / / Delete unwanted error messages IF ((ErrorS == Null) || ErrorS.empty ()) { Request.Removettribute (Error_Key); Return; } / / Save the wrong object we need Request.setttribute (Error_Key, Errors); } If an error occurs, redirect to the input page, and automatically complete the reddle of the input field, the code is as follows: Return (maping.getInput ()))); If you enter user / abc in the landing page, you will prompt the above error, then the original UserName domain will automatically pop up, and a form with a large number of input domains will greatly make it easy. 2. After the above program is performed, this is a legal landing. What we have to do is saving the current user into the session while clearing the invalid FORM bean, and finally turning to the Success page, the code is: return ("Success"); An ActionMApping object corresponds to a global-forwards> This Forward configuration will be valid for all Action. But if there is already an item that is the same name with these global Forward configuration, it will overwrite global configuration. So after you log in, turn to /mainMenu.jsp page. Of course, if you want to define Forward only for an action, let them put them in Part IV: Usage of empty templates In the Struts's WebApps directory contains Struts-Blank.war package, this is a blank frame for Struts. We can use WinRAR and other tools to add Struts-Blank.war to Tomcat. Under WebApps of 5.0.14, start Tomcat, let Tomcat unsubmitted, then delete struts-blank.war. There are three folders and a JSP file in this directory, and the following work is simple. Meta-INF We can do not pay attention to, this folder is extra, this folder is redundant when not involving advanced component techniques or to be EAR or JAR package, because when the WAR package is hit, the package will get everything; Page folder can be placed all JSP files, follow the project to organize the directory, and what is decentralized, don't say it, but for the convenience of the project, you need to organize the structure of the class package, Struts The profile or struts-conf.xml, and the Java file generated by the project is best to put it under the SRC folder, so you can use Ant to compile, that is, your development tool only needs a text editor. Yes, compile work can be handed over to Ant, which will help you complete everything. After using ANT compiles, there is a compiled class file in Classes, of course, it also generates a component package at the same time, you can choose to deploy; as for index.jsp files, you can use the main page of the project.