I'm a struts newbie. I have a Form
, an Action
and a jsp view
.
<form-beans>
<form-bean name="bookEventForm" type="com.example.BookEventForm" />
</form-beans>
<action path="/bookEvent"
type="com.example.BookEventAction"
name="bookEventForm"
input="/WEB-INF/jsp/bookEvent.jsp"
scope="request">
<forward name="success" path="/WEB-INF/jsp/bookEvent.jsp" />
</action>
One of the properties of the event form is Country
so the first thing I do in Action
is:
request.setAttribute("countries", countriesDao.getAll());
in the view I render the select element using:
<html:select property="..." >
<html:optionsCollection name="countries" ... />
</html:select>
This works fine until I add ActionForm#validate to do some validation checks (unrelated to countries, e.g surname != null).
By struts spec as soon as there is an error the Action#execute
never executes. Thus the countries
collection is no longer in the request and the view renders with an empty select element.
I know that I'm most probably missing some core concept of struts. A friend suggested to make the dao available on the view so I can fetch the countries any time but I generaly prefer to prepare the view (prefetch db data) before any JSP "code" is executed.
Any ideas?
What I did to overcome the struts validate
issue was to bypass struts and add my own validate
method on the Form
:
public ActionErrors validate() {
ActionErrors errors = new ActionErrors();
if (...) errors.add("name", new ActionError("error.field.mandatory"));
if (...) errors.add("surname", new ActionError("error.field.mandatory"));
return errors;
}
And call it from the Action
:
saveErrors(request, ((BookEventForm)form).validate());
Works great and fulfills my requirements. The action is now always executed before presenting the view, the error or the success page and has code which prepares the view.