我正在开发 CRUD 应用程序,这有助于统计库存。
我有一个控制器
editDevice()
可以编辑设备的库存卡。在这里,我添加了一个属性“acts”,其中包含以前使用该设备创建的所有操作。设备行为的历史记录显示在 html 表单上。方法 showActsByDevice()
从 postgresql 视图中获取数据。我分别制作了一个控制器updateDevice()
,在其中处理DuplicateKeyException
并返回html表单。
@GetMapping("/{inventoryCard}/edit")
public String editDevice(@PathVariable("inventoryCard") String inventoryCard, Model model){
model.addAttribute("device", deviceDAO.showOne(inventoryCard));
model.addAttribute("acts", actDAO.showActsByDevice(inventoryCard));
return "property/edit_device.html";
}
@PatchMapping("/{inventoryCard}")
public String updateDevice(@ModelAttribute("device") @Valid Device device,
BindingResult bindingResult,
@PathVariable("inventoryCard") String inventoryCard){
try{
deviceDAO.update(inventoryCard, device);
} catch(DuplicateKeyException e){
bindingResult.rejectValue("inventoryCard", "error.inventoryCard", "This inventory card already used");
}
if(bindingResult.hasErrors()){
return "property/edit_device.html";
}
return "redirect:/device/show_all";
}
但是我的模型中没有“acts”属性,因此我无法显示设备的行为。
我尝试使用
redirectAttributes
,但它没有显示错误消息,据我了解,在这种情况下我不应该使用它。
if(bindingResult.hasErrors()){
redirectAttributes.addFlashAttribute("errors", bindingResult.getFieldErrors());
redirectAttributes.addFlashAttribute("device", deviceDAO.showOne(inventoryCard));
redirectAttributes.addFlashAttribute("acts", actDAO.showActsByDevice(inventoryCard));
return "redirect:/device/{inventoryCard}/edit";
}
另外,我无法使用带有
@ModelAttribute
注释的方法,因为我需要设备库存卡的值。
我应该如何处理这个异常并保持html表单上的行为?预先感谢。
我无法使用带有
注释的方法,因为我需要设备库存卡的值。@ModelAttribute
你错了,你可以只使用带有
@ModelAttribute
注释的方法,因为你也可以在其中使用 @PathVariable
。
@ModelAttribute
public void prepareModel(@PathVariable("inventoryCard") String inventoryCard, Model model) {
model.addAttribute("acts", actDAO.showActsByDevice(inventoryCard));
}
这样就可以了。另请参阅文档。