• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Populating a form

 
Rik Sweeney
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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?

Thanks

Richard
 
Merrill Higginson
Ranch Hand
Posts: 4864
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic