Develop Struts using Easy Struts for Eclipse

xiaoxiao2021-03-06  68

How to use Easy Struts plugin

Level: Intermediate

Nancy Chen Junhua

(nancy_chenjunhua@yahoo.com) Software Consultants and Developers May 2004

This article describes how to develop Struts applications using the Easy Struts plug-in in Eclipse IDE. This article first introduces Easy Struts and its installation configuration steps, and introduces how to build a basic Struts application through a step-by-step gradual example. This article also introduces various methods of enhancing Struts applications, such as connecting to databases, modularizing applications, internationalization, and localization, exception handling, and custom plugins. Finally, you will learn how to deploy your Struts application to the Tomcat web server.

Since the Easy Struts plugin can manage all complex configuration files, you can concentrate on the development of program logic. Let us now let's take a look at the 10 features of the Easy Struts to help you build a complete application:

Add easy struts support. Add all required Struts libraries to the project's classpath and create profiles and default resource properties files. Easy form. Create a JSP file with a table single property, as well as the form bean with a table single property and a Setter method, and add a definition of a Form Bean to the configuration file. Easy Action. Create an Action class and add a definition of an operation mapping to the configuration file. Easy Action Associated with a form. Create a JSP file with a table single property, a form bean class with a getter method and a setter method, and an Action class; and add a definition of a Form bean and a definition of an operation mapping to the configuration file. Easy Forward. Create local forwarding and global forwarding, which defines where control should turn. Easy Exception. Treatment exception. Easy Message Resources. Creating a resource attribute file, which is particularly important for the internationalization of the content. Easy Plug-in. Create a plugin. Easy DataSource. Connect the application to a data source. Easy Module. Modular application. In this article, we will introduce 8 in these 10 functions (we will not introduce features 2 and 3). Before starting to develop Struts applications, you should first install all the required programs and plugins, and learn about Java programming, HTML, JSP scripts, and basic knowledge of XML and XSLT. Installation and Configuration Prepare You need to install Eclipse 2.1, Struts 1.1, Tomcat Web Server, and Easy Struts, but also install Sysdeo Tomcat Plug-Ins for Eclipse, MySQL database server, and JDBC Driver for MySQL. Eclipse is an IDE development environment. Struts 1.1 provides libraries that run the Struts application. Tomcat is a Web container for host applications. The Sysdeo Tomcat plugin allows developers to start or stop Tomcat web servers in the Eclipse environment. JDBC Driver for MySQL can convert JDBC calls into network protocols used by MySQL. After installing these software, you need to configure two plugins for Eclipse. Install link on where to download the following software, see the reference part:

Download Eclipse V2.1 from the Eclipse's Web site. You can install it by extracting it to any selected directory (this directory is called Eclipse_home here). Download Struts 1.1 from Apache's Web Sites. You can install it by extracting it to any selected directory (this directory is called struts_home). Download the Tomcat web server from the Apache's Web site. You can install it by extracting it to any selected directory (this directory is called Tomcat_home) in this article. This article assumes that the Tomcat version is V4.1.18. Download the latest Tomcat for Eclipse plugin from Sysdeo's Web site. You can install it by extracting it into the Eclipse_home / eclipse / plugins directory. This article assumes that the Tomcat for Eclipse plugin is V2.2. Download the Easy Struts for Eclipse plugin V0.6.4 from the SourceForge. You can install it by extracting it into the Eclipse_home / eclipse / plugins directory. Download J2SE SDK from Sun's Web Sites. You can install it to any selected directory (this directory is called java_home herein). This article assumes that the J2SE SDK version is V1.4.2. Download the MySQL database from the MySQL Web site. You can install it into any selected directory. Download JDBC Driver for MySQL from MySQL's Web Sites. You should first decompress the downloaded file package and copy mysql-connection / mysql-connector-java-strapple / mysql-connector-java-x.xx-stable-bin.jar to your project workspace. It will also be necessary to return this step behind. This article assumes that the version of JDBC Driver for MySQL is V3.0. Configuration The Sysdeo Tomcat plugin To configure the Sysdeo Tomcat plugin, perform the following steps: Start Eclipse. Configure Tomcat plugins. To implement this feature, click the Window menu, then select the "Preferences" menu item, then select "Tomcat" in the pop-up menu. Then perform the following steps:

Set "Tomcat Version" to Tomcat version number. Set "Tomcat Home" into tomcat_home / jakarta-tomcat-4.1.18. "Perspective to Switch when Tomcat is Started" is set to Java. Add JAR / ZIP for Tools.jar in the sub-option of the Tomcat option, add JAR / Zip for Tools.jar, which should be java_home / lib /. This is used to compile JSP files. Set the ClassPath variable tomcat_home for the project's classpath reference. To complete this task, select the "Java" option in the same pop-up menu as in step 2, then select the "ClassPath Variables" sub-option, and add a new variable "tomcat_home", the path is Tomcat_Home / Jakarta-Tomcat- 4.1.18. Make sure the "Tomcat" menu and 3 toolbar buttons are available. Up to now, we should see a "Tomcat" menu and 3 Tomcat toolbar buttons in the Java view (shown in Figure 1). If you don't see these content, return to the Window menu, select the Customize Perspective ... item, open the option tree, select the "Other" item and select the Tomcat sub-option. Make sure the Sysdeo Tomcat plugin works normally. To verify this, use a menu or toolpower to start / stop Tomcat. Figure 1. Tomcat toolbar button Configuring the Easy Struts plugin To configure the Easy Struts plugin, refer to the contents of Figure 2, and perform the following steps: Select a Struts version. To complete this step, click the Window menu, select the "preference" item, select the "Easy Struts" option and select the "Struts 1.1" tab. Add JARS. "Add Jars" should be added to all the .jar files in the struts_home / jakarta-struts-1.1 / lib directory. Add TLDS. Next, add "Add TLDS" for all .tld files in the struts_home / jakarta-struts-1.1 / lib directory. Figure 2. Configuring the Easy Struts Plug-in Development Struts Application In this section, we will introduce the basic steps to build the Struts application using the Easy Struts plugin. First, you will create a Tomcat project. Then, you will add Easy Struts support for Tomcat projects. Next, you can experience the "Easy Action Associated With A Form" function. After that, you will make the necessary modifications to automatically generate the source code in the previous step. After that, you can test the operation of the application on the Tomcat web server. Finally, you can experience the "Easy Forward" function. Creating a Tomcat project To create a Tomcat project, return to the File menu, select the "New" item and select "Project" in the submenu. Then perform the following steps:

Go to the "Java" option and select "Tomcat Project" and click "Next". Fill in the project name and click "Next" (see Figure 4). Check "Can Update Server.xml File". The server.xml file for the Tomcat web server is automatically updated. Now click "Finish" to complete the task (see Figure 5). The result of creating a Tomcat project is shown in Figure 6. Figure 3. Creating a Tomcat project - Step 1 Figure 4. Creating a Tomcat project - Step 2 Figure 5. Creating a Tomcat item - Step 3 Figure 6. Creating a Tomcat project - Final Result Add Easy Struts Support To add Easy Struts to Tomcat project support, Perform the following two steps: Click the "New" toolbar button, under the "Java" option, select "Add Easy Struts Support" and click "Next" to transfer to the next step (please Referring to Figure 7 - In this article, we refer to this view as an Easy Struts feature view). Set the configuration as shown in Figure 8. Ensure "Copy Struts Binary" and "Copy Struts TLD". The result of adding Easy Struts support is shown in Figure 9. Figure 7. Easy Struts Function View

In Figure 8: Forward them to the active servlet by requesting the container, the URL mode block tells the Struts to process all requests for all matching mode * .do. All other modes of request are not Struts processing. The Default application resource will be created in the web-inf / class / base package / directory. Figure 8. Add Easy Struts Support Figure 9. Add Easy Struts Support - Final Result Diagram 7 shows 10 functions provided by Easy Struts. We have seen the "Add Easy Struts Support". In the rest of this article, we will introduce the remaining seven functions ("Easy Action" and "Easy Form" function is not introduced). In the subsequent sections of this section, we will build a simple but complete Struts application using the Easy Action Associated With a form feature and "Easy Forward" feature. The next section will introduce "Easy Message Resources", "Easy Plug IN", "Easy DataSource", "Easy Exception" and "Easy Module" feature. Use the Easy Action Associated with a form function to return to the Easy Struts function view, select "Easy Action Associated with a form" and perform the following steps to configure the form:

Enter content in USE CASE; FORM name and Form type are automatically generated according to the system's USE CASE. You can manually modify the Form name and Form type (see Figure 10). In the Form property section, click "Add"; add form attributes using the view shown in Figure 11. For example, we add a text input field as shown in the figure: This domain is "tel", the value is "tel", the type Int. We set the initial value of "tel" to 0. When setting "Type", we can enter directly or use the "Browse" function to choose. For the setting of "JSP Input Type", we can also enter directly or from the drop-down list. The Struts system generates a pair of getter methods and setter methods for each table attribute in the Form Bean class. Therefore, for a selection list, you should only create , without creating all . Since you are developing a web application, please select the first two check boxes. Click "Next" to continue. Figure 10. Configuration form

The form of the table cannot be started with uppercase letters. Otherwise, the system will warn that you can't find a getter method when calling your operation. The form is not repeated. If you really want to use two identical attribute names, you can use spaces as a prefix or suffix to solve this problem. Figure 11. Graphical representation of the relationship indicates now, you should see some of the content very similar to Figure 12. By default, the input value is "/form/owner.jsp", which means that the JSP file is placed in the "Easystruts / Form" folder. You can manually modify the location of the JSP file, or the set of Preferenceence. To modify the Preference's settings, enter the "Window" menu, select "Preferences", click the "Easy Struts" option, select the "Style" tab, and set the "JSP Formation" empty. For example, in this article, we tend to save these JSP files directly in the Easystruts folder. Therefore, modify it to "/owner.jsp" as shown in Figure 12. The properties of the operation mapping shown in Figure 12 are as follows:

Path. The relative path of the submitted request. The path name must begin with "/" and unique. TYPE. This ActionMapping is the name of the Action class being described. Attribute. You can access this FORM BEAN request range or a property name of the session range. The condition is that the name is different from the name specified by this bean. Scope. The value of the FORM BEAN that is related to this mapping should be saved. INPUT. It is specified that the control process should return to the relative path of the input form when verifying errors. Validate. If this property is set to True, a form is called an actionform.validate () method to the form associated with this mapping. Parameter. Can be used to pass other information to the ACTION selected by this mapping. Figure 12. Configuration Operation Click "Next", you should see the content similar to that shown in Figure 13. The displayed operation mapping attribute is shown in Figure 13, as follows:

FORWARD. Specifies the relative path to the servlet or JSP resource to process this request. ActionMapping can be converted to this servlet or JSP resource using FindForward. EXCEPTION. ExceptionHandlers associated with this mapping. The forwarding and exceptions here are local, and we will discuss global forwarding and global abnormalities later. Figure 13. Configuring Forward Local Forward Properties:

Name is the only identifier that can be used to return this path in the FindForward () method of the operation map. ContextRelative tag tells Struts The following information:

If this value is set to true, the path is considered to be relative paths relative to the entire web application. If this value is set to false, the path is considered to be a relative path of this module relative to a modular application. If redirect is true, the control process will be forwarded to a redirected page instead of a forwarded page. This means to create a new request. After clicking "finish" (see Figure 14), the system generates com.asprise.struts.form.OWnerM.java and com.Aasprise.java in the EasyStruts / Web-INF / SRC / directory. . At the same time, another file will also generate: Easystruts / Owner.jsp. In the next few sections, you will have some modifications to these three files, thereby completing the entire form, adding the authentication method for users to enter and handles verification errors. Figure 14. Adding a forwarding modification an actionform class to modify all "Integer" in Actionform.java to "Int" because the type of TEL "you just created is Java.lang.integer. The code for writing the Validate () method is written to verify the table single attribute entered. The full code of the validate () method is shown in Listing 1. "Error.Noemail" in ActionError ("Error.Noemail" is a keyword defined in the resource properties file, which is equivalent to "

  • Enter Your Email ". In the resource properties file, you can use the code. The Parameter of the Add (Java.lang.String Property, ActionError Error) method in ActionerRORS is a table single property name. This ActionError can only be related to a specified form. For example, if the email address is empty, or only a space character, the "Enter Your Email" message is displayed when verifying the form. If there is no "@" character in the email address, the "CORRECT Your Email" message is displayed, which is defined using the "Error.Wrongemail" keyword in the resource properties file. These two errors are only related to the form attribute "email" (see Listing 1). We will come back later. Listing 1. Ownerform.java

    Package com.asprise.struts.form;

    Import javax.servlet.http.httpservletRequest;

    Import org.apache.struts.Action.Actionerro;

    Import org.apache.struts.Action.Actionerror;

    Import org.apache.struts.Action.actionform;

    Import org.apache.struts.action.actionmapping;

    Public Class Ownerform Extends ActionForm {

    PRIVATE STRING EMAIL;

    Private string greet = "mr.";

    PRIVATE STRING ADDRESS;

    Private int Tel = 0;

    PRIVATE STRING NAME;

    Public ActionerRors Validate

    ActionMapping mapping,

    HttpservletRequest request) {

    ActionerroS Errors = new actionerrors ();

    IF (greet == null || Greet.trim (). Equals ("")) {

    Errors.Add ("Greet", New ActionError ("Error.greet"));

    }

    IF (Name == Null || Name.trim (). Equals ("")) {

    Errors.Add ("Name", New ActionError ("Error.Name"));

    }

    IF (address == null || address.trim (). Equals ("")) {

    Errors.Add ("Address", New ActionError ("Error.Address");

    }

    IF (email == null || email.trim (). Equals ("")) {

    Errors.Add ("email", new actionerror ("error.noemail");

    }

    Else IF (email.indexof ("@") == - 1) {

    Errors.Add ("Email", New Actionerror ("Error.Wrongemail");

    }

    IF (tel == 0) {

    Errors.Add ("tel", new actionerror ("error.tel");

    }

    Return Errors;

    }

    ...

    Public string getemail () {

    Return email;

    }

    Public void setemail (String email) {

    THIS.EMAIL = Email;

    }

    ...

    }

    code can be used in the resource properties file. The content of the resource attribute file is some key-value pairs (see Listing 2). These keywords can be called in the source code file. In each resource attribute file, you need ErrorS.Header and Erroors.Footer. Listing 2. ApplicationResources.properties

    Errors.Header =

    Validation Error (s)

      Errors.footer =


      Error.greet =

    • choise your greet

      Error.Name =

    • Enter your name

      Error.Address =

    • Enter your address

      Error.tel =

    • Enter Your Contact Numberrror.Wrongemail =
    • Correct Your Email

      Error.Noemail =

    • Enter Your Email

      Modify the Action class Owneraction class to simply display a message such as "Thank you, Miss Nancy Chen" in the local forwarding path "Success". Modify the execute () method of the Owneraction class to implement your logic, (EXECUTE () method must be implemented for each Action class). See Listing 3, which turns the control process to Success.jsp. Listing 3. Owneraction.java

      Public class owneraction extends action {

      Public ActionForward Execute

      ActionMapping mapping,

      Actionform Form,

      HTTPSERVLETREQUEST REQUEST,

      Httpservletresponse response

      Throws exception {

      Ownerform Ownerform = (Ownerform) Form;

      String Greet = Ownerform.getgreet ();

      String name = Ownerform.getname ();

      Request.setttribute ("Name", Name);

      Request.setattribute ("Greet", Greet);

      // forward control to the specified success target Target

      Mapping.Findforward ("Success"));

      }

      }

      Modify the JSP file First, add to , complete the form (see Listing 4). Then add one behind the form, which is used to demonstrate different behaviors with the properties "pre berty". For example, only reflects the authentication of user input related to the table single attribute "name". You can use the ActionerRORS class ADD (String Property, ActionError Error) method to associate some errors for a table single property. will reflect all validation errors in this form. These errors will be displayed in the place where is called. Listing 4. Owner.jsp

      <% @ Taglib Uri = "/ Web-INF / STRUTS-Bean.tld" prefix = "bean"%>

      <% @ Taglib URI = "/ Web-INF / STRUTS-HTML.TLD" prefix = "html"%>

      Name = "generator"

      Content = "Easy Struts Xslt Generator for Eclipse (http://easystruts.sf.net).">

      Struts Form for Ownerform </ Title></p> <p></ hEAD></p> <p><body></p> <p><html: form action = "/ oowner"></p> <p>Greet: <HTML: Select Property = "GREET"></p> <p><html: option value = "> </ html: option></p> <p><html: option value = "mr."> mr. </ html: option></p> <p><html: option value = "miss"> miss </ html: option></p> <p><html: option value = "mrs."> mrs. </ html: option></p> <p></ html: select> <html: errors proty = "greet" /></p> <p>Name: <html: Text Property = "name" /> <html: Errors Property = "Name" /> </br></p> <p>Address: <html: Text Property = "address" /> <html: Errors Property = "address" /> </br></p> <p>Email: <HTML: Text Property = "Email" /> <html: Errors Property = "email" /> </br></p> <p>Tel: <html: text property = "tel" /> <html: errors proty = "tel" /> </br></p> <p><html: submit /> <html: ca ZANCEL /></p> <p></ html: form></p> <p><html: errors /></p> <p><body></p> <p></ html></p> <p>Now, the code Success.jsp displays a message such as "Thank you, Miss Nancy Chen". Among them, "MISS" is the owner's greetings, and "Nancy Chen" is the name of the owner. The final file is shown in Listing 5. Listing 5. Success.jsp</p> <p><% @ Taglib Uri = "/ Web-INF / STRUTS-Bean.tld" prefix = "bean"%></p> <p><% @ Taglib URI = "/ Web-INF / STRUTS-LOGIC.TLD" prefix = "logic"%></p> <p><logic: present name = "name" scope = "request"></p> <p>Thank you,</p> <p><logic: present name = "greet" scope = "request"></p> <p><bean: Write Name = "Greet" scope = "request" /></p> <p></ logic: present></p> <p><bean: Write Name = "name" scope = "request" /></p> <p></ logic: present></p> <p><logic: present> is a struts logic tag. When the logical tag has an attribute "name", you should check if this specified JSP bean is present. See the Struts User Guide for a full list of <logic: present>'s property full list and Struts Logic tag. <bean: Write> is a struts bean tag. It is used to pass the value of the specified bean property to the current JSPWriter. When the bean tag has an attribute "name" and attribute "Property", it means that its property is accessed to obtain the property name of the BEAN of the value specified by "Property". If you do not specify the "Property" property, the value of this bean itself will be passed. For a complete list of <logic: present> properties, and a complete list of Struts Logic tags, see the Struts User Guide. Check Struts-Config.xml When you click Struts-Config.xml in the Eclipse environment, Struts-Config.xml is displayed in a graphical user interface, as shown in Figure 15. This allows developers to easily edit most of the Easy Struts feature. You can also view the source code of Struts-Config.xml by clicking the Source tab. Figure 15. Struts-config.xml Test Application Click the Tomcat toolbar button to restart the Tomcat server. Then enter "http://127.0.0.1:8080/easystruts/owner.jsp" in the URL address bar. Figure 16 will now appear on the screen. The verification results are shown in Figure 17. Note that "PROPERTY" when there is no property "Property". Different behaviors. If you have a "Property" property, the system only returns an error related to this property. If there is no property "Property", the system will return all errors in the form. When all inputs are correct, the system turns the control flow to success, which will display a message: "Thank you, Miss Nancy Chen" (see Figure 18). Figure 16. Owner.jsp Figure 17. Form Verification Error Figure 18. Successfully using the configuration of Easy ForwardStruts provides two ActionForwards, which are global forwarding and local forwarding. The overall ActionForwards is visible for any Action objects in the entire application. Local ACTIONFORWARDS is only available to the Action object that is called from the actionMApping, which is the object associated with local ActionForwards. From the previous section, you have seen how to create a local forwarding during the "Easy Action Associated With A Form". In this section, you will learn how to create local forwarding or global forwarding using "Easy Forward". Go to the Easy Struts function view and click Easy Forward. The result of this should be possible to see the content similar to that shown in Figure 19. If you keep "Visibility" is empty, then the final forwarding is global. If you click the "Browse" button and select "/ Owner", as shown in Figure 20, the final forwarding is local forwarding. Regardless of the forwarding is a global or part, reference is made in mapping.forward ("failure" in the Action class.</p> <p>In the "Easy Action Associated With A Form" section, we have discussed "name", "redirect" and "Context Relative" properties, as shown in Figure 19. Figure 19. Easy Forward - Global Figure 20. Easy Forward - Local Enhancement Application Function In the previous section, we experienced the 3 features of the Easy Struts. In this section, you will write your own XSLT file code, in order to make a certain JSP file style, and use other features to international / localize, connect to the data source, process custom exception, modularize the application. And create a custom plugin. The style of customizing the JSP file using the XSLT file can generate a JSP file according to the required format by writing the .xsl file and configuring the parameters of the Easy Struts. To perform parameter configuration, enter the "Window" menu, select the "preferences" item, select the "Easy Struts" option, and click "XSLT Stylesheet" tab, click "Browse" for "JSP File Stylesheet", add your own .xsl file. For example, the code as shown in Listing 6 is our .xsl file. For each formal property, it generates "Property" and "Value" properties. For example, if you set a text input area named "Name" to "nancy", the code line generated in the JSP file is Name: <html: Text property = "name" value = "nancy"> < / html: text>. Listing 6. Myjsp.xsl Use Easy Message Resource to log content to localize the application by creating a localized resource attribute file. To create a new resource properties file, enter the Easy Struts function view, select Easy Message Resource. The configuration is performed as shown in Figure 21 so that a Chinese message resource will be created. Note that the resource property file name must be ApplicationResources_xx_xx.properties. The lowercase XX represents the local language, it is an ISO-639 language code, two letters; uppercase XX represents a local country, it is an ISO-3166 national code for two letters. Note: About the complete list of ISO-639 language code, visit Languages ​​Page on Unicode.org. For a complete list of ISO-3166 national code, visit Countries Page on Unicode.org. Easy Message Resource Properties:</p> <p>If the NULL property is set to true, an empty string returns to cause unknown message key. This parameter is handed over to the factory when the message resource is bound. The value of "parameter" is the path to the properties file of the Property-File factory. This keyword attribute defines the servletContext property keyword, which is bound to it. Figure 21. Creating a Chinese Message Resource Resource Properties file is easy to edit. You can use Notepad to edit Chinese resource properties files. ApplicationResources_zh_cn.properties should be saved as Unicode (UTF-8) encoding. Then, set the local language to Chinese, set the location to China (on Windows, you can use the area and language options in the control panel). Restart Tomcat to enable modified settings and go to http://127.0.0.1:8080/easystruts/owner.jsp. The verification error is now displayed in Chinese, as shown in Figure 22. Figure 22. Verification Error using Easy DataSource to the database in this section, you will connect the web application to a MySQL database. To implement this feature, enter the Easy Struts function view, select "Easy DataSource" and configure it as shown in Figure 23. Note The JDBC Driver should be placed in the Eclipse_Home / Eclipse / Workspace / Easystruts / Web-INF / LIB directory. Figure 23. Configuring the MySQL Database Next, start the MySQL server and create a database "CRM" and "Owner" as shown in Listing 7. Listing 7. Owner Table # Database: 'CRM'</p> <p># Table structure for table 'Owner'</p> <p>#</p> <p>Create Table 'Owner' (</p> <p>'id' int (6) Not Null Default '0',</p> <p>'Greet' varchar (5) Not null default ',</p> <p>'Name' varchar (50) Not null default ',</p> <p>'email' varchar (50) Not null default ',</p> <p>'address' varchar (100) Not null default '',</p> <p>'tel' int (10) Not null default '0',</p> <p>Primary Key ('ID')</p> <p>) TYPE = MyISAM;</p> <p>Next, modify the Execute () method in the Owneraction class, connect it to the database (see Listing 8). As you can see, Easy DataSource is here using these Key properties. "Org.apache.struts.Action.data_source" is the keyword used by the data source. Note We caught SQLException and reappeared it. In the next section, you will encode the exception handler to handle the SQLException exception. Listing 8. Owneraction.java - Database connection</p> <p>Public ActionForward Execute</p> <p>ActionMapping mapping,</p> <p>Actionform Form,</p> <p>HTTPSERVLETREQUEST REQUEST,</p> <p>HttpservletResponse response) throws exception {</p> <p>Ownerform Ownerform = (Ownerform) Form;</p> <p>String Greet = Ownerform.getgreet ();</p> <p>String name = Ownerform.getname ();</p> <p>Request.setttribute ("Name", Name);</p> <p>Request.setattribute ("Greet", Greet);</p> <p>String address = ownerform.getaddress ();</p> <p>String email = Ownerform.Getemail ();</p> <p>INT tel = Ownerform.gettel ();</p> <p>Connection conn = NULL;</p> <p>Statement Stmt = NULL;</p> <p>ResultSet RS = NULL;</p> <p>DataSource DataSource = (DataSource) servlet.getServletContext (). GetAttribute (</p> <p>"org.apache.struts.action.data_source");</p> <p>Try {</p> <p>CONN = DataSource.getConnection ();</p> <p>STMT = conn.createstatement ();</p> <p>INT ID = 0;</p> <p>RS = Stmt.executeQuery ("SELECT MAX (ID) AS Counter from Owner);</p> <p>While (rs.next ()) {</p> <p>ID = RS.Getint ("counter");</p> <p>}</p> <p>ID = 1;</p> <p>Stmt.executeUpdate ("INSERT INTO OWNER VALUES</p> <p>" ID ", '" Greet ",' " name ", '" address " "" tel ")");</p> <p>Rs.close ();</p> <p>Stmt.close ();</p> <p>CONN.CLOSE ();</p> <p>}</p> <p>Catch (SQLException E) {</p> <p>Throw New Sqlexception ("Database Error");</p> <p>}</p> <p>// forward control to the specified success target Target</p> <p>Mapping.Findforward ("Success"));</p> <p>}</p> <p>You should restart the Tomcat server, let it connect to the data source at startup, and go to http://127.0.0.1:8080/easystruts/owner.jsp page. If all inputs are correct, then insert a record in the "Owner" table and turn the control to the Success.jsp page. You can check the database to confirm if a record is inserted in the table "Owner". Using the EASY Exception Process As mentioned in the previous section, you can write your own exception handler to handle SQLException exceptions. First, enter the Easy Struts function view, select Easy Exception to declare an exception. Use the configuration shown in Fig. 24. This exception's message resource is stored in the resource package name, which is specified in the bundle property. This abnormal property indicates that the class is handled to handle this exception when this exception occurs. This keyword is defined in the message resource package. When an exception occurs, the control process is redirected to a file given in the PATH property. The Scope property tells Struts ActionerRors (created when processing an exception) should be saved (session or request). The Type property specifies the exception type that this exception handler will intercept. Figure 24. After the exception is clicked "Finish", it is declared. Then you should write the code of myExceptionHandler.java (see Listing 9). It extends the ExceptionHandler class, which is similar to the Action class, and also implements an Execute () method, and returns an ActionForward object. As you can see, Easy Exception's "path" property can be obtained using the getPath () method of the ExceptionConfig class. You can get this Key property using the getKey () method of the ExceptionConfig class. Listing 9. MyExceptionHandler.javaPackage com.asprise.struts.exception;</p> <p>Import javax.servlet. *;</p> <p>Import javax.servlet.http. *;</p> <p>Import org.apache.struts.Apache.struts.action. *;</p> <p>Import org.apache.struts.config. *;</p> <p>Public class myexceptionhandler extends ExceptionHandler {</p> <p>Public ActionForward Execute</p> <p>Exception EX,</p> <p>ExceptionConfig AE,</p> <p>ActionMapping mapping,</p> <p>Actionform FormInstance,</p> <p>HTTPSERVLETREQUEST REQUEST,</p> <p>Httpservletresponse response</p> <p>Throws servletexception {</p> <p>Request.setttribute ("MyException", EX);</p> <p>Request.setttribute ("MyForm", FormInstance);</p> <p>Request.setttribute ("mykey", ae.getKey ());</p> <p>Return New ActionForward (AE.GetPath ());</p> <p>}</p> <p>}</p> <p>In the abnormal statement, if a SQLException exception occurs, the control flow will be redirected to the Exception.jsp file. Our exception.jsp displays the message of the keyword "error.Database" in the default resource property file, as well as the exception type and exception message when the exception is thrown. You can get this exception key in MyExceptionHandler. You can also use this keyword to use it to the <bean: Message> label, as shown in Listing 10. Listing 10. Exception.jsp <% @ Page Import = "java.sql.sqlexception"%></p> <p><% @ Page Import = "com.asprise.struts.form. *"%></p> <p><% @ Taglib Uri = "/ Web-INF / STRUTS-Bean.tld" prefix = "bean"%></p> <p><%</p> <p>Ownerform myform = (ownerform) Request.GetaTribute ("MyForm");</p> <p>IF (MyForm! = null) {</p> <p>Out.println ("<font color = red> sorry," myform.getgreet ());</p> <p>Out.println ("" myform.getname () "</ font>");</p> <p>}</p> <p>%></p> <p><ul> <bean: Message Key = "<% = Request.GetaTRibute (/" mykey / "). TSTRING ()%>" /></p> <p><%</p> <p>Object obj = request.getattribute ("MyException");</p> <p>IF (Obj! = null) {</p> <p>Throwable ex= (throwable) OBJ;</p> <p>Out.println ("<li> <b> type: </ b>" ex.toT7tring ());</p> <p>Out.println ("<li> <b> message: </ b>" ex.getMessage ());</p> <p>}</p> <p>%></p> <p>Define "Error.Database = <h3> an Exception Handled by MyExceptionHandler: </ h3>". When a SQLException exception occurs, you should see the content shown in Figure 25. Figure 25. Processing exception - Test results Using Easy Module Modules to the application in this section, we will create a new module named "newModule". To implement this feature, enter the Easy Struts function view, select "Easy Module" and enter "newModule" in Module Name, as shown in Figure 26. Figure 26. The configuration module restarts Eclipse to enable new modules. If this error occurs when starting a web application: org.xml.sax.saxparsexception: the content of element type "servlet" must match "(icon?, Servlet-name, display-name?, Description?, (Servlet- Class | JSP-file, INIT-param *, load-on-startup?, run-as?, security-role-ref * ", by moving the new module configuration section directly into a default in web.xml Module below, you can solve this problem. There are two ways to switch to a new module. First, you can create a new global or local forwarding "Success" in Struts-Config.xml (see Listing 11). You can then switch to this new module using mapping.findforward ("Success"). Listing 11. Forward <forward name = "success"</p> <p>ContextRelative = "true"</p> <p>PATH = "/ newmodule / index.do"</p> <p>REDIRECT = "true" /></p> <p>Second, create an operation as shown below, which is a SwitchAction action:</p> <p><action path = "/ switchto" type = "org.apache.struts.Actions.switch" validate = "false" /> then creates the operation mapping shown in Listing 12 in Struts-Config-NewModule.xml. Listing 12. Operation mapping</p> <p><action-mappings></p> <p><action path = "/ index" type = "com.asprise.struts.newmodule.Action.indexaction"></p> <p><forward name = "success" Path = "/ index.jsp" /></p> <p></ action></p> <p></ action-mappings></p> <p>Next, write the code of Easystruts / NewModule / Index.jsp. Index.jsp only displays a message "<H1> You are in module: newModule </ h1>". Now, start the Tomcat server and enter http://127.0.0.1:8080/easystruts/switchto.do?prefix=/newmodule&page=/index.do. The result is shown in Figure 27. If you want to switch back to the default module, simply enter http://127.0.0.1:8080/easystruts/switchto.do?prefix=&page=/owner.jsp. Figure 27. Switching between modules Note: You can specify a module name in all Easy Struts feature other than "Add Easy Struts Support". Creating a custom plugin using Easy Plug-in this section, you will learn the last feature of Easy Struts - Easy Plug-in. One common usage of Plug-in Action is to configure or load data for a specific application at the time of the web application. The custom plugin implements a PLUG-IN interface. The implementation of this interface requires a constructor of a zero parameter for an ActionServlet to ensure that the plugin can be created correctly. The two methods defined in the interface are init () and destroy (), which are called when the application is started and turned off, respectively. You must implement these two methods. To create a plugin, enter the Easy Struts function view, select Easy Plugin, enter the content in the Plugin Class, and add some properties. We have to add Proxy and Port properties as shown in Figure 28. Figure 28. Configure the plugin Next, write the code of the MyPlugin class, as shown in Listing 13. This code implements the Plugin class. When starting a web application, a message says "MyPlugin Starting" and sets the system's Proxy and Port properties. A "MyPlugin stopping" message is displayed when the application is turned off. Listing 13. MyPlugin.javaPackage Com.asprise.struts.plugin;</p> <p>Import org.apache.struts.action.plugin;</p> <p>Import org.apache.struts.config.moduleconfig;</p> <p>Import org.apache.struts.action.ActionServlet;</p> <p>Public class myplugin implements plugin {</p> <p>Public String Proxy;</p> <p>Public string port;</p> <p>Public myplugin () {</p> <p>}</p> <p>Public void init (ActionServlet Servlet, ModuleConfig Config) {</p> <p>System.err.print ("****************");</p> <p>System.SetProperty ("https.proxyhost", getProxy ());</p> <p>System.SetProperty ("https.proxyport", getport ());</p> <p>servlet.getServletContext (). SetAttribute ("proxy", getProxy ());</p> <p>Servlet.getServletContext (). SetAttribute ("port", getport ());}</p> <p>Public void destroy () {</p> <p>System.err.Print ("****************");</p> <p>}</p> <p>Public void setProxy (string prox) {</p> <p>Proxy = prox;</p> <p>}</p> <p>Public string getproxy () {</p> <p>Return this.Proxy;</p> <p>}</p> <p>Public void setport (String Por) {</p> <p>Port = POR;</p> <p>}</p> <p>Public string getport () {</p> <p>Return this.port;</p> <p>}</p> <p>}</p> <p>In this source code for this JSP or other Java file, getServletContext () can be used to get the value of Proxy ("Proxy". To deploy the Struts application to the client, you can simply export the application as a WAR file and distribute it to your client, let them put this WAR file in your Web server. " WebApps "directory. Below is the step of exporting an application as a WAR file:</p> <p>Go to the "Project" menu, select the "Properties" menu, select the "Tomcat" option and click the "Export to War Settings" tab. Click "Browse" on the edge of "WAR File for Export", set it to your selected folder /easystruts.war, and save the settings. Then enter the Project pop-up menu, select "Tomcat Project" and click "Export to The War File Sets in Project Properties" in the submenu. After displaying the "Operation Successful" message, you can go to the location specified in step 2 to get the WAR file. Conclusion In this article, we introduce the features of the Struts application that Easy Struts is developed on the Tomcat web server. You have learned how to deal with form validation, how to create local and global forwarding and exceptions, and also know how abnormal processing, how to connect data sources, content, and modularize applications, create self Define plugins and deploy applications to clients. Reference</p> <p>Download the source code in this article. Download Struts 1.1 from Apache's Web Sites. Download Eclipse V2.1 from Eclipse's Web Sites. Download Easy Struts for Eclipse Plugin V0.6.4 from SourceForge. Read "Struts User Guide" on Apache's Web site. On Mastering Jakarta Struts, a guide to build JAVA web applications by Jakarta Struts Framework (JAVA Web App) written (John Wiley & Sons, 2002) is given on Mastering Jakarta Struts. The Struts framework is described in detail in James Turner and Kevin Bedell's Struts Kick Start (Sams, 2002). If experienced programmers need a Struts guide, see struts in action in TED N. Husted, Cedric Dumoulin, George Francus, and David Winterfeldt (MANNING PUBLICATIONS Company, 2002). For a complete guide to developing an Eclipse plug-in, see the Java Developer's Guide to Eclipse (Addison Wesley Professional, 2003) in John, Scott Fairbrother, John KEHN, Scott Fairbrother, John Kellerman, and Pat McCarthy. You can find more articles provided by Eclipse users on the developerWorks Linux area, you can find the latest Eclipse download address on AlphaWorks. On the Open Source Area of ​​Developer Bookstore, hundreds of books on open source code are found, including several books on Eclipse and books on Struts applications. About the author Nancy Chen Junhua is a free software consultant and developer with years of experience. She also engaged in Agent Learning in Nanyang University of Science and Technology Singapore. You can contact her through nancy_chenjunhua@yahoo.com.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-111592.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="111592" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.053</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'U_2BtrupASSjrGH_2FO8CPghr1XnhDpkDdHLdg7NBcgbBGgFr_2BBwj8doHeO_2FNz_2BcWqu_2FLAyMjuO5cf2GNJmDf7dG7g_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>