Consider the following scenario:
-
My form model
public class PersonForm { @NotNull private String name; /*usual getters and setters*/ } -
My controller:
@Controller @SessionAttribute(types={ PersonForm.class }) public class MyController { @RequestAttribute(...) public String render(final ModelMap map) { /* get list of info and for each info * create a PersonForm and put it in the modelmap * under key p0, p1, p2, ..., pn */ } public String submit(final ModelMap map, @Valid final PersonForm form, final BindingResult result) { if (result.hasErrors()) { // return to page } else { // do necessary logic and proceed to next page } } } -
And finally my JSP view
... <c:forEach ...> <form:form commandName="p${counter}"> ... other form:elements and submit button goes here </form:form> </c:forEach> ...
As you can see I am trying to handle multiple forms of the same class type. The submit works — it gets me to the submit(…) method just fine, and so does the validation. However re-rendering the page does not show me the expected error messages!
Even worse — I checked what is being passed in the submit header and there is no indication whatsoever which form submitted, so there is no way to discriminate between one form on another. This led me to believe multiple forms of the same class type is not possible …
Is there any other way I could do this (apart from Ajax) ?
Many thanks.
I managed to get this ‘hack’ to work. It is as what jelies has recommended so the credit goes all to him.
In simple terms, the concept is to pre-fill your view using the traditional
<c:forEach>construct. The tricky part is whenever the ‘Submit’ button of that respective row is pressed, all of the information must be injected into a hidden form and force-submitted to the Controller. If the screen is rendered again with some errors, the script must be responsible of injecting the values back to the respective rows including the errors.1) My model
2) My controller
3) My view
As you can see the view has the hairiest parts — hopefully it will still proves to be useful for anyone who (unfortunately) comes across the same situation as mine. Cheers!