It's not a secret anymore!
The moose likes Struts and the fly likes Populating a form Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Struts
Bookmark "Populating a form" Watch "Populating a form" New topic

Populating a form

Rik Sweeney
Ranch Hand

Joined: Sep 04, 2001
Posts: 36

Is it possible to repopulate a Form from a database? Basically I have an EmployeeForm and I want to use the same EmployeeEdit.jsp file, so what I have done is pass over the Employee ID I want to edit to my Action. The EmployeeFactory will then retrieve the user and populate the form. My JSP is not populated though. Here is the code

Is this the correct way to populate a form?


Merrill Higginson
Ranch Hand

Joined: Feb 15, 2005
Posts: 4864
This is one of those Java "gotchas". Before Struts calls your execute() method, it creates an instance of ActionForm and puts it in either request or session scope depending the scope you specified in the action mapping in your struts-config.xml file. Struts then passes that instance to your execute() method as a parameter. If you use the instance passed in as a parameter by casting it to the appropriate subclass, and calling it's getters and setters, that instance is the one that will be used by your JSP and everything is fine.

However, what you've done is replace the variable "form" with a new instance of your ActionForm bean. The form variable is local to your execute() method, and the instance of ActionForm that it contains now is not the same instance that is currently in request or session scope, and consequently is not the same instance that will be used by your JSP.

There are two different ways to fix this:

1. (Preferred) Don't create a new instance of the ActionForm, but use the one passed in as a parameter.

2. Put the instance of the ActionForm you created in request or session scope with exactly the same name used in your <form-bean> tag in struts-config.xml. The disadvantage of this method is that if you decide to change either the name or the scope of the bean, you will have to remember to change your code as well.

Consultant, Sima Solutions
I agree. Here's the link:
subject: Populating a form
It's not a secret anymore!