5.1. Creating Dynamic Action Forms

Problem

You want to create ActionForms for use on your pages without having to handcode a unique Java class for each form.

Solution

Create a form-bean in the struts-config.xml file using the built-in DynaActionForm type or any of its subclasses. Then define the properties of the form using nested form-property elements:

<form-beans>
  <form-bean name="MyForm" type="org.apache.struts.action.DynaActionForm">
    <form-property name="foo" type="java.lang.String"/>
    <form-property name="bar" type="java.lang.String"/>
    <form-property name="baz" type="java.lang.Boolean"/>
    <form-property name="blindMice" type="java.lang.String[]"
                   size="3"/>
  </form-bean>
<form-beans>

You can retrieve the data from the form using methods of the DynaActionForm or generically using the Jakarta Commons PropertyUtils class. The Action shown in Example 5-1 uses this technique to get the form property values by name.

Example 5-1. Using PropertyUtils with ActionForms

package com.oreilly.strutsckbk.ch05; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.PropertyUtils; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class ProcessAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ...

Get Jakarta Struts Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.