How to update two entities/model elements from one jsp in Spring MVC?

泪湿孤枕 提交于 2019-12-07 14:07:12

问题


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.


回答1:


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.




回答2:


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" />


来源:https://stackoverflow.com/questions/12230216/how-to-update-two-entities-model-elements-from-one-jsp-in-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!