Struts Principles and Practices (2)

Source: Internet
Author: User
Tags tld

Next, we will start with a simple logon example to have a clear and intuitive understanding of the main parts of struts. This example is very simple. Assume that there is a user named LHB whose password is aWave. The task to be completed by the program is to present a logon interface to the user, if both the name and password entered by the user are correct, a welcome page is returned to the user. Otherwise, the logon page is returned, asking the user to log on again and display the corresponding error information. This example is used repeatedly in the basic section of struts. This simple program is used as an example because we do not want to dilute our theme with overly complicated business logic.

Because struts is a framework built on the MVC design pattern, you can follow the standard development steps to develop your struts web application. These steps can be roughly described as follows:
1 Define and generate all views representing the user interfaces of the application, and generate all actionforms used by these views and add them to the struts-config.xml file.
2. Add the necessary messageresources project to the applicationresource. properties file.
3. Generate the application controller.
4 define the relationship between views and controller in the struts-config.xml file.
5. model components required for generating applications
6. Compile and run your application.

Next, we will follow the steps above to complete our application:

Step 1: The Views section of our application contains two parts. JSP page: one is the login page logon. JSP. The other is the main function page after successful user logon. JSP. Currently, this page is just a simple welcome page.

The code list of Logon. jsp is as follows:

     
      <%@ page contentType="text/html; charset=UTF-8" %><%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %><%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %><HTML><HEAD><TITLE><bean:message key="logon.jsp.title"/></TITLE>

The main. JSP code list is as follows:

     
      <%@ page contentType="text/html; charset=UTF-8" %><%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %><%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %><HTML><HEAD><TITLE><bean:message key="main.jsp.title"/></TITLE>

First, let's take a look at the logon. jsp file and we will find that it has two distinctive features: first, the file header includes:

The role of such command code is to instruct the page to use struts custom tags. The tag library URI is a logical reference, and the tag library Descriptor (TLD) is located on the web. see the configuration section in the previous article. The struts tag library consists of four groups of tags:

  • Bean tag, used to manipulate bean in JSP
  • Logic tag, used for process control in JSP
  • HTML tags are used to display forms and other components.
  • Template tag to generate dynamic templates

    The specific functions and syntax of each type of tag are not discussed here Due to space limitations. You can refer to the struts manual and other materials. I just want to understand that some classes are behind tags, which are similar to beans. They run on the backend and generate standard HTML tags and return them to the browser.

    To use them, we obviously need to introduce their tag library description files into our system. These are some files with the. TLD extension. We need to put them in /Webapps/mystruts/WEB-INF/directory. After the struts tag is introduced, the common HTML Tag, such as the text box tag, is changed to this form. .

    The second feature of JSP files is that the pages do not directly write text for display, such as username and password, but use This form appears. This feature lays a solid foundation for international programming. later articles on international programming will be discussed in detail.

    The actionform used by this simple application is userinfoform. The code list is as follows:

          
           package entity;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionMapping;import javax.servlet.http.HttpServletRequest;public class UserInfoForm extends ActionForm{  private String username;  private String password;  public String getUsername() {    return (this.username);  }  public void setUsername(String username) {    this.username = username;  }  public String getPassword() {    return (this.password);  }  public void setPassword(String password) {    this.password = password;  }}
          

    Create another classes directory under the WEB-INF directory of your application, and create the following directories under the newly created classes directory entity (used to store the actionform class), Action directory (used to store the action class), and bussness directory (used to store the business object class as the model ). The sub-directories under the classes directory are called packages. In the future, the corresponding packages will be added as needed.

    Now, save userinfoform. Java to the entity directory.

    Add the following code /Webapps/mystruts/WEB-INF/struts-config.xml File

          
           <form-beans>    <form-bean name="userInfoForm" type="entity.UserInfoForm" />  </form-beans>
          

    Note that the case sensitivity of the actionform must be followed by the above Code to avoid unnecessary troubles.

    At this point, we have completed the first step.

    Step 2: create a file named applicationresource. properties and put it in /Webapps/mystruts/WEB-INF/classes directory. It's the configuration information in the struts-config.xml we 've mentioned at the end of the first article, that is:

    The following content is added to the applicationresource. properties file:

          
           #Application Resource for the logon.jsplogon.jsp.title=The logon pagelogon.jsp.page.heading=Welcome World!logon.jsp.prompt.username=Username:logon.jsp.prompt.password=Password:logon.jsp.prompt.submit=Submitlogon.jsp.prompt.reset=Reset#Application Resource for the main.jspmain.jsp.title=The main pagemain.jsp.welcome=Welcome:
          

    At this point, we have completed the second step.

    Step 3: Generate and configure the Controller component.

    As we have mentioned earlier, the struts application controller is composed of Org. apache. struts. action. actionservlet and org. apache. struts. action. action class. The former is already prepared by struts. The latter struts only provides a skeleton for us. What we need to do is to expand the action class to implement specific functions of the application, the following is a list of code that implements the action class of the login program:

          
           
    Package action; import Java. io. ioexception; import javax. servlet. servletexception; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpsession; import javax. servlet. HTTP. httpservletresponse; import Org. apache. struts. action. action; import Org. apache. struts. action. actionerror; import Org. apache. struts. action. actionerrors; import Org. apache. struts. action. actionform; import Org. apache. struts. action. actionforward; import Org. apache. struts. action. actionmapping; import Org. apache. struts. action. actionservlet; import bussness. userinfobo; import entity. userinfoform; public final class logonaction extends action {public actionforward execute (actionmapping mapping, actionform form, httpservletrequest request, response) throws ioexception, servletexception {userinfoform = (userinfoform) form; // obtain the username and password string username = userinfoform from the web layer. getUserName (). trim (); string Password = userinfoform. getPassword (). trim (); // declare the error set object actionerrors errors = new actionerrors (); // verify the input if (username. equals ("") {actionerror error = new actionerror ("error. missing. username "); errors. add (actionerrors. global_error, error);} If (password. equals ("") {actionerror error = new actionerror ("error. missing. password "); errors. add (actionerrors. global_error, error);} // call the business logic if (errors. size () = 0) {string validated = ""; try {userinfobo = new userinfobo (); Validated = userinfobo. validatepwd (username, password); If (validated. equals ("match") {// if everything is normal, the user information is saved and switched to the successful page httpsession session = request. getsession (); Session. setattribute ("userinfoform", form); Return Mapping. findforward ("success") ;}} catch (throwable e) {// handle possible errors E. printstacktrace (); actionerror error = new actionerror (E. getmessage (); errors. add (actionerrors. global_error, error) ;}}// if an error occurs, go to the input page and display the corresponding error message saveerrors (request, errors); return New actionforward (mapping. getinput ());}}
          

    This action class has two error message keys to be added to the applicationresource. properties file. The list is as follows:

          
           #Application Resource for the LogonAction.javaerror.missing.username=<li><font color="red">missing username</font></li>error.missing.password=<li><font color="red">missing password</font></li>>
          

    Step 4: define the relationship between views and controller in the struts-config.xml file, that is, configure the so-called actionmapping. They are positioned in the struts-config.xml
    ... Tag, the configuration of our login program is as follows:

          
           <action-mappings>    <action input="/logon.jsp" name="userInfoForm" path="/logonAction" scope="session" type="action.LogonAction" validate="false">      <forward name="success" path="/main.jsp" />          </action>  </action-mappings>
          

    Step 5: generate the model component required by the application. This component is used to complete the application business logic. Now, the business logic of my login application is very simple, it is to determine whether the user is LHB and whether the password is aWave. If yes, it returns a matching string "match". Otherwise, an error message is thrown. The code list is as follows:

          
           package bussness;import entity.UserInfoForm;public class UserInfoBo {  public UserInfoBo(){      }    public String validatePwd(String username,String password){        String validateResult="";            if(username.equals("lhb")&&password.equals("awave")){      validateResult="match";    }    else{            throw new RuntimeException("error.noMatch");    }            return validateResult;         }}
          

    Put it in the bussness package.

    We also need to set the key value indicating the error message in the applicationresource. properties file. The list is as follows:

          
           #Application Resource for the UserInfoBo.javaerror.noMatch=<li><font color="red">no matched user</font></li>
          

    So far, we have completed all the components of this simple logon program. Now we can enjoy the fruits of our work.

    Step 6: Compile and run the application.

    The general practice is to use ant to assemble and deploy struts applications. If this rule is followed, this article will be very tedious and not necessary, because, an IDE can easily generate an application. Therefore, we use a simple method to directly compile our. Java file. However, it should be noted that, in order to ensure that the compilation process is not wrong, you must copy the Struts. jar file /Common/lib directory, and set the classpath value in the environment variable /Common/lib/struts. Jar. After configuration, You can compile the. java files in the entity, bussness, and Action directories respectively. After compilation: Open Add the following statement to the server. xml file in the/conf directory to create a virtual directory for our application:

          
           <Context path="/mystruts" docBase="mystruts" debug="0"                 reloadable="true">                 </Context>
          

    Start Tomcat. Enter http: // localhost: 8080/mystruts/logon. jsp in the browser
    If the previous steps are not disclosed, a logon screen will appear in front of you.

    If you click the submit button without entering any content, it will return to logon. JSP displays the missing username and missing Password error messages. If other content is entered, no matched user error is returned; if the user name is LHB and the password is aWave, the welcome page indicating successful logon is displayed.

    Although the above is a simple application, although it is small and dirty, it basically involves the main components of struts. Next we will analyze the features and basic working principles of the program.

    First, enter in the browser. when a JSP file is created, the backend will translate the custom struts tag into a common HTML Tag and return it to the browser, some prompts, such as the username, password, and button prompts of the label in the input box, are from messageresources, that is, applicationresource. the key value in the properties file. When we click the submit button, we can see from the Web. xml configuration that the request will be intercepted by actionservlet. It looks for the corresponding item in the struts-config.xml file through the action parameter provided in the form, if there is a corresponding actionform, it fills the corresponding attribute of the actionform with the form data, in this example, the actionform is userinfoform and the corresponding attributes are username and password. This is the so-called instantiated actionform. Then, give the control to the corresponding action. In this example, It is logonaction. The main task is to verify the username and password retrieved from the actionform, here is just a simple test of whether they are empty (these simple validation of formatting should be done on the client side, and Struts also provides us with a good mode, ). If it is not empty, call userinfobo, the business logic module that determines whether the user and password are correct. At the same time, it will capture Possible errors, then, the program is directed to different pages based on the results returned by the business logic. In this example, if the result returned by the business logic is "match ", Returns main. the JSP page saves the user's login information to the browser at the same time in the session object; otherwise, the input page is returned and the corresponding error information is displayed, completing the four main responsibilities described in the previous article.

    You must have noticed that, in the business logic module userinfobo of this example, the user and password are written to the program and will not be used in a real application, information that needs to be permanently stored, such as username and password, will be stored in permanent media such as database files. The next article will introduce how to access the database in struts.

  • 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.