This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
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
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.