如何从一个jsp在Spring MVC中更新两个实体/模型元素? [英] How to update two entities/model elements from one jsp in Spring MVC?
问题描述
我的要求是通过向用户提供一个表单,在JSP中使用来自两个实体(例如 UserDetails 和 EmploymentDetails )的输入字段来执行CREATE操作。
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)
使用单个提交在单个jsp中更新两个表单的最有效方法是什么?
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?
请指导。
推荐答案
一个常见的做法是将任意数量的对象放在包装类中,并使用此对象以单一形式提交数据。此外,您可以在任何对象中使用JSR-303验证:
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;
...
}
形式:
<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>
和您的控制器:
@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();
...
}
方法是通过JSON保存对象,但我认为在这种情况下是过度和过于复杂。
Another approach is to save objects via JSON, but I think is overkill and overcomplicated in this case.
这篇关于如何从一个jsp在Spring MVC中更新两个实体/模型元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!