Tuesday, November 1, 2011

Prepopulating form in Struts

I learned quite a few things when revisited Struts after a long time. Thought I could share some of these.

The simplest way to prepopulate a form is to have an Action whose sole purpose is to populate an ActionForm and forward to the servlet or JSP to render that form back to the client. A separate Action would then be use to process the submitted form fields, by declaring an instance of the same form bean name.

Let us take a look at the following example. Note the following definitions from the struts-config.xml file:

<action name="testCycleForm" path="/getlaunchdetails" scope="request" type="launch.action.GetLaunchDetailsAction" validate="false">
   ...
</action>
<action name="testCycleForm" path="/starttestcycle" scope="request" type="launch.StartTestCycleAction" input="page.starttestcycle">
  ...
</action> 


Note the following in this approach:

  • Both actions use the same form bean.
  • When the /starttestcycle action is entered, the framework will have pre-created an empty form bean instance, and passed it to the execute() method. The setup action is free to pre-configure the values that will be displayed when the form is rendered, simply by setting the corresponding form bean properties.
One aspect to be aware is how you type-cast the form in the execute method of GetLaunchDetailsAction. The correct way is

TestCycleForm cycleForm = (TestCycleForm) form;

Typecasting of the following type would not yield the desired result.

TestCycleForm cycleForm = new TestCycleForm();
// Populate values
form = cycleForm;

As far as the JSP is concerned, all is required is the property field appropriately pointing to the fields in the bean.

A couple of pointers in this regard - 
  • In JSP, do not give the name attribute in the Struts html tags unless you want to be hindered with the "Cannot find xxx in any scope" issue.
  • Populating  html:select tags can be a bit tricky. Consider the following example
       <html:select property="OS">
        <html:option value="select">-- Select --</html:option>
        <html:option value="linux">Linux</html:option>     
        <html:option value="windows">Windows</html:option>
        <html:option value="mac">Mac</html:option>
    </html:select>

       If you were to pre-populate the value for OS prior to form load, as before all you need to do  is set the form in your Action1 (GetLaunchDetailsAction). Just ensure that the value assigned matches the one inside the value field defined in the JSP. Here, setOS("mac") would be the correct approach and not setOS("Mac").

No comments:

Post a Comment