What i know: actionformbean that we create is a sub class of ActionForm
Now let’s suppose we create…
Struts action form bean: productbean.java
Struts action class: productaction.java
In productaction.java’s execute() method:- I did
{
productbean p1 = new productbean();
String n =p1.getName(); // calling the getter, that returns the product name
}
But n is null, when written into database
With this in execute method everything works fine:
{
productbean p1 = (productbean)form; // downcasting of ActionForm object
String n = p1.getName();
}
My question is if actionclass and formbean are in same package, why can’t we just create an object of the formbean and call its getter function in actionclass? Why downcasting of ActionForm object is necessary?
Because if you create a new ProductBean instance and get the name from this new instance, you will always get the default value of the name property (null, typically), instead of the value that was extracted from the
namerequest parameter, stored into the ProductBean instance that Struts has created and has passed to theexecute()method of your action.When a request comes in for your action, Struts instantiates the form bean, populates it with the request parameters, and invokes your action with the form bean. If you create another form bean instance, it will not get magically populated with the request parameters.
What you’re doing is similar to the following: