Struts ActionForm Class

In this post we will learn about the ActionForm in detail. This example will help you understand Struts in detail. We will create user interface to accept the address details and then validate the details on server side. On the successful validation of data, the data will be sent to model (the action class). In the Action class we can add the business processing logic but in this case we are just forwarding it to the sucess.jsp.
What is ActionForm?
An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.
We will first create the class AddressForm which extends the ActionForm class. Here is the code of the class:

The above class populates the Address Form data and validates it. The validate() method is used to validate the inputs. If any or all of the fields on the form are blank, error messages are added to the ActionMapping object. Note that we are using ActionMessage class, ActionError is now deprecated and will be removed in next version.
Now we will create the Action class which is the model part of the application. Our action class simply forwards the request the Success.jsp. Here is the code of the AddressAction class:



Now we have to create an entry for form bean in the struts-config.xml. Add the following lines in the struts-config.xml file:

Now create Address.jsp, which is our form for entering the address details. Code for Address.jsp is as follows:

User enter the values in the form and click on the submit form. Form validation is done on the server side and error message is displays on the jsp page. To display the error on the jsp page <html:errors/> tag is used. The <html:errors/> tag displays all the errors in one go. To create text box <html:text …/> is used in jsp page.

Above tag creates text box for entering the address. The address is retrieved from and later stored in the property named address in the form-bean. The tag <html:submit>Save</html:submit> creates the submit button and the tag <html:cancel>Cancel</html:cancel> is used to create the Cancel button.
Add the following line in the index.jsp to create a link for testing the Address.jsp form:

Build the application and click on the Test the Address Form link on the index page to test the newly created screen. You should see the following screen.

In this lesson you learned how to create data entry form using struts, validate and finally send process the business logic in the model part of the struts


Leave a Reply

Your email address will not be published.