Application of Jakarta Struts Learning

Source: Internet
Author: User
In this article, we will explain the application of struts step by step. In this way, we open the door to struts's unique mystery. Through this process, I believe it will also inspire you to apply struts in application development. If you are not clear about struts terms, refer to the previous article about struts in this series.

Repeat it again. This article requires the reader to have the following knowledge and experience: JSP, Servlets, custom tag Library (custom tag libraries) and XML. In addition, in this article, I will also use other good items of the Jakarta Project Team, such as atathttp: // jakarta.apache.org/tomcat/index.html (to implement the Java Servlet and JSP official standard servlet containers, in general, it is a JSP web server) and anthttp: // jakarta.apache.org/ant/index.html (Java-based automatic compilation and publishing tool, which is a good idea ).

As a technician who has been using cutting-edge technologies to develop many applications, I have always believed that mastering new technologies and understanding the logic of technology development is crucial. But this is often the quagmire of our learning pace. For this reason, I plan to use the complete process developed by struts as a case study. The case of this process can be described as "the sparrow is small and has full data." You can apply this process to the complicated and huge projects at hand, at least it works well to apply this process in our big projects.

Developers who develop complex commercial applications know that customers' requirements are constantly changing. Therefore, if there is a set of standardized development processes to follow, when customers propose new requirements, we can at least clarify what "unreasonable" needs are actually reasonable and feasible. Well, next I will show you and apply the entire process in my example.

The sample code in this article is part of the strutssample application. complete code including build. XML can be downloaded at http://www.onjava.com/onjava/2001/10/31/examples/strutspartii.jar.

Struts Development Process

From the version number released by struts, we can see that struts is a new thing. It consists of several parts. It is wise to know when the appropriate part should be developed, that will make better use of our development time. From the several struts applications I have developed, I have summarized the following effective development steps:

1. Define application requirements;

2. Define and design each user interface from the perspective of user input and data acquisition;

3. determine the access path of the user interface;

4. The actionmapping table is determined by the application logic information );

5. Develop the classes and application functions used on the designed user interface;

6. Develop actionform and corresponding data verification methods based on data information on the user interface;

7. actionmapping will be called or transferred to the corresponding JSP page. In this step, we will first develop these actions;

8. Developing commercial application logic is the corresponding JavaBean, EJB or other stuff;

9. Develop a system workflow defined by actionmapping to complete the corresponding JSP page;

10. Complete the system configuration file: struts-config.xml and web. xml;

11. Compile, test, and release.

Define Application Requirements

The first step in developing any application system is to collect user requirement information. No matter how reasonable a user logic looks at the beginning, it is always possible to find it much harder than it looks at development. Therefore, we recommend that you create a clear list of user requirements. This is not just for the purpose of development. You can also use this table to analyze user requirements to determine which areas may require more effort.

In our strutssample project, the application requirements are:

As a complete example showing the Struts framework application, this example completes the function of user logon. The purpose is only to clarify struts applications. This example will not involve the security, database, EJB development, and other related technologies that may be used in general complex application systems.

Design User Interface

This application includes the following three user interfaces:

1) logon interface, used for user name and password input;

2) Welcome Page when the login user is a legal user;

3) Error prompt page when logon fails.

Determine the access path of the user interface

1) the logon interface is the default page of the application;

2) The welcome page can be accessed only after successful logon;

3) any page that may cause an error can enter the error prompt interface;

Actionmapping determined by application logic informationActionmapping defines actionmapping in the configuration file struts-config.xml to streamline the process of application processing by forwarding requests, determine the action of each user request in the application. Usually we gradually determine the information required by actionmapping in the development process, the process of developing code is to improve the struts-config.xml step by step from the draft. After the action class processes user requests, the returned forward is defined in actionmapping. There are multiple possibilities for a forward returned by an action, although an action generally only defines several of its associated forward. If multiple actions may return the same forward, you can define it as global forwarding ). This is similar to the global variable in the header file in C. If in the struts-config.xml description, a forward is not defined in the current action description but globally, then this global variable will take effect, similarly, the forward defined in an action overwrites the global definition. In this simple example, we define a global forward-"error". When the forward returned by an action is the error ing of "error", then errorpage. the JSP page is displayed to the user, although the current action is not defined for it. We continue to develop and improve the project, and the configuration files related to the project will become more and more detailed. In the following example, we will take the struts-confug.xml file used in strutssample as an example to learn the definition of the ing between global forward and an action. The following defines an action named "login", which is com. oreilly. actions. for loginaction instances, when action processes the user's successful login, it returns a forward rule named "success", and the user will see welcome. on the JSP page, if logon fails, action returns the corresponding forward to display login. JSP is provided to the user. If other errors occur during the processing, action will return the globally defined forward-"error", and the user will see the error page errorpage. JSP.


     
      
<! -- =========== Global forward definition --> <global-forwards> <forward name = "login" Path = "/login. JSP "/> <forward name =" error "Path ="/errorpage. JSP "/> </Global-forwards> <! -- =========== Action mapping definition --> <action-mappings> <! -- <Action> related attributes of an element --> <! --
     

The following lists common attributes. For more information, see org. Apache. Struts. Action. actionmapping.

Path-path of the user request URI corresponding to the current action

Type-complete name of the Java class implementing the current action

Name-the name of the actionform used in the current action. The specific information is defined in detail elsewhere in the configuration file.

Unknown-if this attribute is set to true, declaring this action will process all requests not found in the application that process the action. Of course, in an application system, only one action's unknown attribute can be set to true.

The lifetime of the actionform used in scope-action can be "request" or "session". With the lifecycle settings, the action will be created at the corresponding time.

Input-The actionform in this action obtains the user input page. When the actionform is set to automatically verify the input data and an error is returned when illegal data is found, this page is returned.

Validate-if this attribute is true, the validate method of the corresponding actionform will be automatically called before the action, which is generally used to verify the data entered by the user.

Forward element-define actionforward related to the current action


     
      --> <!-- =================== --> <!-- O'Reilly Struts Sample Main Actions --> <!-- =================== --> <action path="/login" type="com.oreilly.actions.LoginAction" name="loginForm" scope="request" input="/Login.jsp"> <forward name="success" path="/Welcome.jsp"/> <forward name="failure" path="/Login.jsp"/> </action> </action-mappings>
     

In the previous article, we once said that struts-config.xml is the controller of the MVC pattern. When identifying configuration information in the struts-config.xml, you should spend more time on it to ensure that each action definition and its associated definitions meet the needs of the application. If there is no detailed design definition at the beginning of the project, when all the code and configuration are integrated, we will inevitably re-organize the code and configurations of each part. In our current example, strussample only processes user logon, so only one action is required. The number of actions used in an application system depends on the size of the application. Once the full set of action ing is fully defined, we can develop the specific implemented action and actionform classes one by one, and gradually integrate the completed part of the 1.1 points.

Develop the classes and application functions used by the designed user interfaceAll actionform implementation classes are subclasses of org. Apache. Struts. actionform. An actionform is associated with a single-phase input table on the page, and the implementation of actionform can also verify the legitimacy of user input data. As a Java Bean, actionform has the set and get methods. When a form in a page is submitted, the system will automatically call the Set Method to put the data into actionform, the get method is provided to operate the data in the action. Generally, processing all the data in the form and verifying validity can be done by actionform. In applications, I personally prefer to divide actionform and action into different packages, because when several pairs of actionfrom and action are used in a page, it will be obfuscated if they are all placed in a package. The following code is the actionform code used on the logon page of the instance.


     
      
/** Loginform. java */package COM. oreilly. forms; import javax. servlet. HTTP. httpservletrequest; import Org. apache. struts. action. actionerror; import Org. apache. struts. action. actionerrors; import Org. apache. struts. action. actionform; import Org. apache. struts. action. actionmapping;/*** verify the two data required by the user ** username-Logon username * password-User Password **/public final class loginform extends actionform {private string username = NULL; private string Password = NULL;/*** get method of username * @ return string */Public String GetUserName () {return (username );} /*** Set Method of username * @ Param username */Public void setusername (string newusername) {username = newusername ;} /*** get method of password * @ return string */Public String GetPassword () {return (password );} /*** Set Method of password * @ Param password */Public void setpassword (string newpassword) {Password = newpassword ;} /*** reset all data ** @ Param mapping current actionmapping * @ Param request the httpservletrequest currently being processed by the server */Public void reset (actionmapping mapping, httpservletrequest request) {username = NULL; Password = NULL;}/*** verify the data submitted by the current HTTP Request * If the data verification finds that the data is invalid, returns an actionerrors object encapsulated * All verification errors *. If the data passes verification, this method returns NULL or an actionerrors object * @ Param mapping current actionmapping * @ Param request the httpservletrequest currently being processed by the server */Public actionerrors validate (actionmapping mapping, httpservletrequest request) {actionerrors errors = new actionerrors (); // In the current actionform, you only need to check the user name data entered by the user if (username = NULL | username. length () = 0) {errors. add ("username", new actionerror ("error. username. required ");} return (errors );}}
     

The above code is different from the Java Bean in general. The first is the reset method. The value set in the method will be reflected to the corresponding form item when the form is reset, that is, restoring the data of the form item to the default value. The second is the validate method, which is used to verify the data entered by the user in the form. In the current example, only the user name entered by the user is verified. Because the password of a user name may be blank, our logic is that the password is not checked during verification. Verify the username. If the entered username is blank, an error object (actionerror) is generated in the method ).

Multiple errors are loaded using actionerrors in struts. From the "S" ending with actionerrors, we can know that she is a collection of actionerror objects. When verifying user input, you can verify all the data in the form and then return multiple possible errors to the user through actionerrors. This logic should be taken for granted, it is impossible for a user to have five different input errors, but the user should be prompted five times. Let the user submit the changes five times.

At the same time, we need to know that in our example, we will prompt the error message to the user through the applicationresource. properties file. This file is defined as used by this application in Web. xml when Tomcat is started. Usually every application has a web. xml file in its WEB-INF directory to describe the system, and for detailed structure information for Application Deployment, see tomcathttp: // jakarta.apache.org/tomcat/index.htmlserverrelated user manual.

In the applicationresource. properties file, you can define the string of the prompt information to be used in the application. The string uniquely determines its position through a key value. In our example, the key value is error. username. the string information corresponding to required is "a username is required". When an error message is displayed to the user, the string is displayed through the key value-determined error prompt. This mechanism facilitates the implementation of multiple languages in the system and translates the strings in the file into the corresponding language, our system can be used in Spanish, German, French, Chinese, and other languages.

The following applicationresource. properties information is sufficient for our simple example:


     
      login.title=Login Struts Sample error.userName.required=A username is required error.login.authenticate=Invalid username/password errors.footer=</ul>

You can use this file to define the display strings for the page title, button, or other text prompts. In the last article in this series, that is, the subsequent development steps, we will explain how to use the struts tag to obtain the display string from this file.

To be continued

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.