Struts Work Instruction manual

Source: Internet
Author: User
Tags add object definition config contains empty version java web

Author: Junsan Jin

Date: 2005-4-4

Version: 1.0

Mailbox: junsan21@126.com; Junnef21@sohu.com

Disclaimer: I reserve all the rights of this article.


The first part: Introduction
Struts began in March 2000 as an open source framework for developing Web applications using the Java servlet/javaserver pages technology.







Struts can be used to develop a Java Web front-end application based on the MVC (Model-view-controller) design pattern. The MVC design pattern usually divides a system into three parts that work together:







1, model (model), models used to encapsulate the state of the system, such as business data;







2, view (view), the representation of the model, provides a user interface. When the state of the model changes, the view should be notified so that the changes in the model can be updated;







3, Controller (Controller), accept requests 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 (the Controller servlet, the org.apache.action provided by struts). The Actionservlet class implementation) and the action (Org.apache.action.Action subclass) responsible for the specific business logic, one for the display of the JSP page (Viewer), and the other for the Business logic component (Model) that encapsulates the state of the system. The central controller of Struts accepts all requests from the client, and routing HTTP requests to other action objects (the Org.apache.struts.action.Action subclass of the developer implementation) according to the system configuration (struts-config.xml). All of the business operations are done in these action objects, such as inserting an order, modifying a record, and so on. After processing, the controller servlet of struts moves to the appropriate JSP page based on configuration, displaying the results of the processing to the user. As you can see from here, the controller servlet plays an important role in struts, which controls all program flows and coordinates the three relatively independent parts of MVC to make the system more functional.






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 the jakarta-struts-20031118 version (attached to the 1.1 version series) to download the address:

http://jakarta.apache.org/builds/jakarta-struts/release/



We get the installation package Jakarta-struts-20031118.zip.




Part III: Installation configuration Struts1, installation struts
Unzip the Jakarta-struts-20031118.zip package into the E:\mylib\jakarta-struts. It contains Lib and webapps two subdirectories. The Lib subdirectory is the jar file, the tag library definition file (. tld) that is required for struts, and the DTD definition (. dtd) of the Web.xml and Struts-config.xml configuration files for a struts Web application. The WebApps subdirectory contains several examples of struts that have been packaged in the. war format, which mainly introduces three of them:







1. Struts-example.war, a simple example program using the Struts framework controller;



2. Struts-documentation.war,struts documentation of the war package;



3. Struts-blank.war, a blank struts application, can be easily modified and configured with its own application.







If we want to build a new application, we'll use the third as the basic framework.






2. Operation Struts-example.war
Copy the Struts-example.war into the WebApps directory under Tomcat. Then start Tomcat,tomcat will automatically extract the war package at startup (if you don't extract it automatically, see if your Tomcat server is configured to run the war document directly), enter http://localhost:8080/in the browser Struts-example, if you can see the page shown in the following illustration, you are already running successfully.

















In the above picture you can click "Register with the" Mailreader Demonstration Application "Register a mailreader user, or click" Log on to "Mailreader directly Demonstration Application ", enter the username and password (the sample program has preset a user user/pass, configured in Web-inf\database.xml file under Struts-example) to log in.


3, the analysis of the routine (1) web.xml analysis


In the page shown above, click the "Log on to" Mailreader Demonstration Application link, enter the/logon.jsp page, enter the predefined username user, password for pass, The submission is then entered into the user's home page as shown in the following figure.















Note that the suffix for the URL here is. do. So what's the point of it? How does a server handle 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 fragment:







<!--Action Servlet Mapping-->

<servlet-mapping>

<servlet-name>action</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>





As you can see from the above configuration code, the request URL with the. Do end is handled by a servlet named action, which can actually take another suffix for the application, as long as it is modified here.







Look at the following section of the configuration summary:







<!--Action Servlet Configuration-->



<servlet>



<servlet-name>action</servlet-name>



<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>



<init-param>



<param-name>application</param-name>



<param-value>



Org.apache.struts.webapp.example.ApplicationResources



</param-value>



</init-param>



<init-param>



<param-name>config</param-name>



<param-value>/WEB-INF/struts-config.xml</param-value>



</init-param>



......



<load-on-startup>2</load-on-startup>



</servlet>





Visible from the top, the action corresponding to the class is Org.apache.struts.action.ActionServlet. This is a central-controlled servlet provided by struts, the controller servlet, that listens to all of the user's requests for the. do suffix. In the above configuration, an initialization parameter named Config is configured for Actionservlet, and the value is/web-inf/struts-config.xml. Struts-config.xml is the most important configuration file based on struts application, which contains all the action requests (that is, requests with a. Do end), the corresponding action handler class, the Form Bean, and the page's steering. Struts-config.xml is read in when the application is started, and then responds according to these configurations. The following is an example of the configuration of the logonaction in the example program, and the Struts-config.xml is analyzed.






(2) Struts-config.xml analysis
The following are some of the code for configuring Logonaction in Struts-config.xml:







<action



Path= "/logon"



Type= "Org.apache.struts.webapp.example.LogonAction"



Name= "LogonForm"



Scope= "Request"



input= "/logon.jsp" >



</action>





As can be seen from the above, mailreader applications in the corresponding/logon.do request is by Org.apache.struts.webapp.example. Logonaction class, the Name property specifies the model component for the form that corresponds to the request.







LogonForm is also configured in Struts-config.xml, and the following is part of the code for its configuration:







<form-bean name= "LogonForm"



Type= "Org.apache.struts.validator.DynaValidatorForm" >



</form-bean>







The LogonForm class is a common JavaBean that defines the reading and writing methods for several properties and attributes, and the names of these properties correspond to the input fields in the page form. For example, two attributes are defined in LogonForm, and the code is as follows:







Private String username = null;



Private String password = null;







The two properties correspond to the two input fields in the Logon.jsp form, and the code is as follows:























Note here that the property name in the LogonForm must correspond exactly to the form domain name in the logon.jsp. Struts is the result of fetching the submitted data from the browser side and populating it in the LogonForm object, and then sending it to the Logonaction class for processing. The same is true with the form validation and refill technology implemented by struts. In the above page code we used the struts HTML custom tag library, these tags are defined in struts in the tag library, the intended study can look, but recommended that the best to use less, because these tags support javascript events are very small, and lost the support of automatic backfill, Therefore, it is better to do the extension tag yourself. You can also use the HTML code similar to <input type= "text" name= "username"/> to find it in the tag library of struts.






(3) Action analysis
Above we have a certain understanding of the overall structure and data flow of struts front end application framework. Also know how struts from the configuration file to obtain configuration information, that is, first start, then wait for the request, and then crawl data from the front, according to the configuration information called (or generated) Action class processing, and finally according to the results of processing to the corresponding page response user. So now let's look at how Logonaction is doing business and displaying the results of the processing to the user. 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 {



......



Actionerrors errors = new Actionerrors ();



String username = ((logonform) Form). GetUserName ();



String Password = ((logonform) Form). GetPassword ();



......



Perform user authentication



If this user is not present, or if the password is incorrect, the error is added to the errors



if (!errors.empty ()) {



Saveerrors (request, errors);



Return (New Actionforward (Mapping.getinput ()));



}



HttpSession session = Request.getsession ();



Session.setattribute (Constants.user_key, USER);



Delete an expired form bean



......



if (Mapping.getattribute ()!= null) {



if ("Request". Equals (Mapping.getscope ()))



Request.removeattribute (Mapping.getattribute ());



Else



Session.removeattribute (Mapping.getattribute ());



}



Navigate to the Success page



Return (Mapping.findforward ("Success"));



}



}



}







The Logonaction class inherits from the Org.apache.struts.action.action,action class, which is the base class for all the action. The defined perform () method completes the processing of the request and shifts to a different page based on the processing result, which is then displayed to the user. The action class is not a servlet, and it does not listen directly to requests from clients. The central controller Actionservlet mentioned above is a servlet, the client sends the action request, receives by the Actionservlet, according to Struts-config.xml in the configuration, passes on the corresponding mapping, form, Request, the response object, and call the corresponding action class's perform () method for processing (instantiating an action on the first call, the subsequent request will directly call the existing action class for processing, so the action class is shared, Attention should be paid to dealing with concurrency problems in programming. 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. We might wonder when these two attributes were placed? This is actionservlet to place the LogonForm object by fetching the data from the front-end request based on the configuration in Struts-config.xml and the properties in the corresponding logonform before calling the Logonaction perform () method. User authentication is then performed. This example does not use a database for storage, and the user information is stored in the Database.xml file. If Username/password does not exist in the Database.xml file or if the password is incorrect, a Actionerror object is generated, the error message is stored in the object, and the object is added to the actionerrors, and other errors occur similarly. In the subsequent program, the first check whether there are errors, if there is an error occurred, the wrong object is stored in the request, the method used is saveerrors (request, errors). This method is implemented in the base class Org.apache.struts.action.Action, it completes the function is very simple, the errors object is stored in the request through the setattribute () method. Implemented as follows:







protected void Saveerrors (HttpServletRequest request,actionerrors errors) {



Remove unwanted error messages



if ((Errors = null) | | Errors.empty ()) {



Request.removeattribute (Error_key);



Return



}



Save the wrong objects we need



Request.setattribute (Error_key, errors);



}







If an error occurs, it is redirected to the input page, and the input field is automatically filled in with the following code:





Return (New Actionforward (Mapping.getinput ()));



If you enter USER/ABC on the landing page will prompt the above error, then the original input of the username field will be automatically populated, in a large number of input fields of the form will greatly facilitate the user.







2. After the above procedure is passed, it means that this is a legal landing. All we have to do is save the current user to the session, erase the form Bean that is already invalid, and finally turn to the success page with the code:







Return (Mapping.findforward ("Success"));







A Actionmapping object corresponds to a <action/> configuration in the Struts-config.xml. If you are careful, you may have discovered that in the configuration of the/logon action for example in Struts-config.xml, there is no forward configuration, but at the beginning of it there is a global forward configuration. The configuration code is as follows:







<global-forwards>



<forward name= "Logoff" path= "/logoff.do"/>



<forward name= "logon" path= "/logon.jsp"/>



<forward name= "Success" path= "/mainmenu.jsp"/>



</global-forwards>







This forward configuration will work for all the action. However, if you already have an item with the same name as these global forward configurations, it overrides the global configuration. So after you login successfully, you will be directed to the/mainmenu.jsp page. Of course, if you want to define a forward that works only on one action, put them in the <action/>.






Part IV: Use of empty templates
The Struts-blank.war package is included in the WebApps directory of struts, which is a blank frame of struts. We can use tools such as WinRAR to untie the Struts-blank.war package, or put it under the WebApps of Tomcat 5.0.14, start Tomcat, let Tomcat unpack the package, and then delete the Struts-blank.war.





This directory has three folders and a JSP file, the following work is simple. Meta-inf we can ignore that this folder is redundant without the advanced component technology or the ear or jar package, because the Packer will fix everything when the war package is played, and the page folder can place all the JSP files, Organize the catalogue according to the project needs; and web-inf What, needless to know, but in order to facilitate the maintenance of the project, you need to organize a good package of structure, Struts profile is still struts-conf.xml, the Java file generated by the project is best placed under the SRC folder, so you can use ant to compile, that is, your development tools only need a text editor on it, the compilation work can be given to ant, it will help you accomplish everything. When you use ant to compile a compiled class file under classes, of course, it also generates a component package, you can choose to deploy one, and the index.jsp file can be completely replaced by the project's main page.





Ok,struts's configuration is so simple that it says enough for a project to be used. Of course, struts has more advanced applications that can go to the help documentation for struts, which is the Struts-documentation.war, deployed to Tomcat to browse.





Note: This document is the first draft, if there is anything to add or find any errors, please contact promptly in order to add or correct.




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.