Struts - A Quick How-ToBy: Abdul Habra Version: 0.12 Date: July 19, 2002 Table Of Contents1 Introduction1.1 Development Platform 1.2 Prerequisites 1.3 Struts Application Creation Steps 2 Creating The Application 2.1 Determine Form's Name 2.2 Determine Data Entry Fields 2.3 Create Blank Struts Application 2.4 Create Form Class 2.5 Create Action Class 2.6 Create JSP Form Page 2.7 Create Response Page 2.8 Review web.xml 2.9 Update struts-config.xml 2.10 Run JSP Form Page 3 Validation 3.1 Modify JSP Form Page 3.2 Modify struts-config.xml 3.3 Add Error Messages To ApplicationResources.properties 3.4 Add validate() Method To Bookform.Java 3.5 Run JSP Form Page 4 Conclusion 5 References 1 IntroductionThis document describes how to create a simple form-based Struts application. From a user's perspective, the application consists of the following:
The following two figures show the desired pages: This document does not explain the theoretical background of Struts (e.g. MVC), nor try to convince the reader to use Struts. Please refer to the references section to learn more about Struts. 1.1 Development PlatformWe will develop the application on a machine configured with the following:
1.2 PrerequisitesReader should be familiar with:
1.3 Struts Application Creation StepsCreating a Struts application (with a form) consists of the following steps:
2 Creating The Application2.1 Determine Form's NameStruts uses a name (similar to a variable's name) to associate a form in the JSP to the Form and Action classes. Select a name that reflects the function of the form. For example if the form is to ask for a book definition, name it "book".2.2 Determine Data Entry FieldsDetermine what are the data entry fields that will be displayed on the form. These names will be used in:
2.3 Create Blank Struts ApplicationThe Struts download comes with a blank struts application that can be used to start the development of a Struts application. Please make sure that you have downloaded and installed the Struts binaries, and then do the following:
2.4 Create Form ClassCreate a new Java class with the following characteristics:
package com.tek271.test; import javax.servlet.http.*; import org.apache.struts.action.*; public class BookForm extends ActionForm { private String mTitle= null; private String mAuthor= null; public String getTitle() { return mTitle; } public void setTitle(String aTitle) { mTitle= aTitle; } public String getAuthor() { return mAuthor; } public void setAuthor(String aAuthor) { mAuthor= aAuthor; } public void reset(ActionMapping aMapping, HttpServletRequest aRequest) { mTitle= null;
mAuthor= null; } // reset() } // BookForm class Notice that the class extends the ActionForm class and defines a reset() method. When you compile this class, make sure that the struts.jar and servlet.jar are available to the compiler. However, do not put struts.jar in the CLASSPATH. To compile the class:
2.5 Create Action ClassCreate a new Java class with the following characteristics:
package com.tek271.test; import javax.servlet.*; import javax.servlet.http.*; import org.apache.struts.action.*; public class BookAction extends Action { public ActionForward perform(ActionMapping aMapping, ActionForm aForm, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException { BookForm f = (BookForm) aForm; String title = f.getTitle(); String author = f.getAuthor(); System.out.println(">>> Saved: " + title + " by " + author); return aMapping.findForward("saved"); } // perform() } // BookAction class Notice the following about the perform() method:
To compile this class, follow the steps of section 2.4 using BookAction instead of BookForm. 2.6 Create JSP Form PageCreate a JSP file named testJsp.jsp and save it into:%TOMCAT_HOME%/webapps/struts-test/ The following is its source code: <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <html> <head> <title>Testing struts</title> </head> <body> <html:form action="book.do" > Title: <html:text property="title" /> <br> Author: <html:text property="author" /> <br> <html:submit /> </html:form> </body> </html> Notice the following about this file:
2.7 Create Response PageCreate a JSP file named savedOk.jsp and save it into:%TOMCAT_HOME%/webapps/struts-test/ The following is its source code: <html> <head><title>Book was saved</title> </head> <body> <h3>Book Was Saved</h3> </body> </html> Note that this is just a simple page to give a response to the user. 2.8 Review web.xmlThis is an optional step. You do not need to do any thing with this file. However, understanding it will be useful.Open the following file in a text editor: %TOMCAT_HOME%/webapps/struts-test/WEB-INF/web.xml The following is the section of the file that we are interested in: <web-app> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>application</param-name> <param-value>ApplicationResources</param-value> </init-param> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <!-- some more stuff ... --> </servlet> <!-- Standard Action Servlet Mapping --> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- some more stuff ... --> </web-app> Notice the following about this file:
We can restate the above as: When Tomcat receives a URL ending with "*.do", it will map this URL to the Struts framework, and tells Struts to use the configuration file struts-config.xml. 2.9 Update struts-config.xmlWhen you created the blank application, the following file was created:%TOMCAT_HOME%/webapps/struts-test/WEB-INF/struts-config.xml This file contains the configuration data for Struts in our application. Update this file to the following: <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.0//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd"> <struts-config> <form-beans> <form-bean name="bookForm" type="com.tek271.test.BookForm"/> </form-beans> <action-mappings> <action path="/book" type="com.tek271.test.BookAction" name="bookForm"> <forward name="saved" path="/savedOk.jsp" /> </action> </action-mappings> </struts-config> Notice the following about this file:
2.10 Run JSP Form PageIn a web browser window, go to the following link:http://localhost:8080/struts-test/testJsp.jsp You should see something like this: Enter some data in the text boxes, for example: Title: King Lear Author: William Shakespeare When you push "Submit", you should see a new page like this: If you inspect the Tomcat console window, you should see a line with the following text: >>> Saved: King Lear by William Shakespeare 3 ValidationIn this section we will add validation support to our program. The following steps summarize the required steps:
You will notice how simple this is, and how the data entered in a form will get repopulated automatically when the form is redisplayed. In the following sections, new lines have a gray background. 3.1 Modify JSP Form PageModify testJsp.jsp to look like this:<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <html> <head> <title>Testing struts</title> </head> <body> <html:errors/> <html:form action="book.do" > Title: <html:text property="title" /> <br> Author: <html:text property="author" /> <br> <html:submit /> </html:form> </body> </html> Line 5 is a tag that will print the errors in an ActionErrors object. 3.2 Modify struts-config.xmlModify the file struts-config.xml to be like this:<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.0//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd"> <struts-config> <form-beans> <form-bean name="bookForm" type="com.tek271.test.BookForm"/> </form-beans> <action-mappings> <action path="/book" type="com.tek271.test.BookAction" name="bookForm" input="/testJsp.jsp"> <forward name="saved" path="/savedOk.jsp" /> </action> </action-mappings> </struts-config> The "input" attribute (line 13) tells Struts what is the page that started this form, and in case of validation errors, this page will be used to redisplay the input data. 3.3 Add Error Messages To ApplicationResources.propertiesThe file ApplicationResources.properties exists in the \WEB-INF\classes directory of the application. Modify it to be like this:index.title=Struts Starter Application index.heading=Hello World! index.message=To get started on your own ... error.book.title=<li>Title is required</li> error.book.author=<li>Author is required</li> errors.header=<h3>Errors:</h3><UL> errors.footer=</UL><hr> Lines 4 and 5 have the name of the error messages and their text. Line 6 is a prefix to be displayed before the error messages. Line 7 is to be appended after the error messages. 3.4 Add validate() Method To Bookform.JavaAdd the following method to the BookForm.java class:public ActionErrors validate(ActionMapping aMapping, HttpServletRequest aRequest) { ActionErrors err = new ActionErrors(); if ((mTitle==null) || (mTitle.length() <1) ) err.add("title", new ActionError("error.book.title") ); if ((mAuthor==null) || (mAuthor.length()<1) ) err.add("author", new ActionError("error.book.author") ); return err; } //validate
3.5 Run JSP Form Page
Notice how the error message is displayed, and how the Title field retained its data. 4 ConclusionAs you have seen, using Struts requires some thinking and planning before you start coding (Something new for a change :)).The example we did in section 2 shows how to start using Struts but does not show any advantages, it actually adds both programming and performance overhead. If you decide to add validation and error handling using Struts, you will start to see the advantages that Struts brings you. 5 References
|
Documents > Java Related >