使用spring MVC,我将如何创建一个不映射到实体的表单(即它具有来自多个实体的属性)。
我还想验证和使用具有错误集合等的“结果”对象。
网上有这方面的例子吗?我需要看到它才能理解它(新手)
使用spring MVC,我将如何创建一个不映射到实体的表单(即它具有来自多个实体的属性)。
我还想验证和使用具有错误集合等的“结果”对象。
网上有这方面的例子吗?我需要看到它才能理解它(新手)
您只需创建一个包含表单所需的所有属性的新类,并将其用作表单的模型属性。在接听电话时,您也可以使用此类型。Spring 会自动为你绑定属性。您还应该考虑使用 JSR-303 验证注释。
一般的方法是加载所有必要的实体,以从 GET 请求创建表单支持对象。然后将该表单支持对象放入模型中。在 POST/PUT 请求中,您必须重建实际触及的实体。通常,您会再次加载它们并将新提交的部分数据应用到它们。
一般来说,构建一个专用组件来处理该组装行为可能是一个好主意,这样您就不会用该代码污染控制器。
/**
* Prepares the form by setting up a custom form backing object.
*/
@RequestMapping(value = "account/{id}", method = GET)
public String processGet(@PathVariable("id") Long id, Model model) {
Account account = accountService.getAccount(id);
return prepareForm(dtoAssembler.createFormFor(account), model);
}
/**
* Process form submission. Uses JSR-303 validation and explicit error
* handling.
*/
@RequestMapping(value = "account/{id}", method = PUT)
public String processGet(@ModelAttribute("accountForm") @Valid AccountForm form, Errors errors, Model model) {
if (errors.hasErrors()) {
return prepareForm(form, model);
}
Account account = accountService.getAccount(form.getId());
accountService.save(dtoAssembler.applyData(account, form));
return "redirect:/accounts";
}
/**
* Populates the given {@code Model} with the given {@code AccountForm}
* and returns the view to show the form.
*/
private String prepareForm(AccountForm form, Model model) {
model.addAttribute("accountForm", form);
return "account";
}
我只是在这里这样写,以强调正在发生的事情。在现实世界的场景中,我可能会让 DtoAssembler 使用服务完成所有工作(所以我会将服务注入到汇编器中)。
为了方便使用 Dozer、BeanUtils 或类似的东西将数据从 DTO 传输到域对象中,这可能是合理的。