Managing dynamic form elements in Struts

Those who are working with Struts, it could be a great problem if you have dynamic form elements in your form and you need to manage them. As they are dynamic, you dont know what are their name and you ant actually map these properties into your ActionForm bean. So how to manage these dynamic form elements, any idea? Take a look at this solution below.

First, Lets make your ActionForm bean like this

public class TestBean extends ActionForm {

public final Map values = new HashMap();

public void setValue(String key, Object value)
{
values.put(key, value);
}

public Object getValue(String key)
{
return values.get(key);
}
}

here comes the action in struts-config

Now we need to see how we can map dynamic properties in JSP pages.

Submit This

Please note that we add “value()” – thus it will access the Setter method setValue() in our ActionForm bean.

Finally, lets capture the submitted dynamic values in our Struts Action

public class TestAction extends Action {
public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

TestBean tb = (TestBean) actionForm;
httpServletRequest.setAttribute(“dynamic”, tb.getValue(“dynamic”)); //first dynamic
httpServletRequest.setAttribute(“dynamic2”, tb.getValue(“dynamic2”)); //second dynamic
return actionMapping.findForward(“success”);
}
}

Well, you can just go thru the HashMap in TestBean for all the dynamic values.