My requirement is to do a CREATE operation by providing the user with a form in a JSP with input fields from two entities (e.g. UserDetails and EmploymentDetails)
What is the most effective way to update two forms in a single jsp using a single submit?
One approach I know of is to combine the two entities into a single wrapper-class and then send that object as Model. Is that the only solution?
Kindly guide.
It's a common practice to put any number of objects in a wrapper class and use this one to submit data with a single form. Additionally, you can use JSR-303 validation in any of objects:
public class MyForm {
@Valid
private UserDetails userDetails;
@Valid
private EmploymentDetails employmentDetails;
...
}
your form:
<form:form modelAttribute="myForm" method="post">
<form:input path="userDetails.property1"/>
<form:input path="userDetails.property2"/>
<form:input path="employmentDetails.property1"/>
<input type="submit" value="create"/>
</form:form>
and your controller:
@RequestMapping(value = "/", method = RequestMethod.POST)
public ModelAndView create (@Valid MyForm myForm, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
// here you can retrieve form errors of both objects
}
UserDetails userDetails = myForm.getUserDetails();
EmploymentDetails employmentDetails = myForm.getEmploymentDetails();
...
}
Another approach is to save objects via JSON, but I think is overkill and overcomplicated in this case.
Could try mapping each object to different model attribute:
public String create(@Valid @ModelAttribute(value="UserDetails") UserDetails userDetails,
@Valid @ModelAttribute(value="EmploymentDetails") EmploymentDetails employmentDetails,
BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest)
{
In the form, these should be bound to different prefixes, eg:
<form:input path="UserDetails.name" />