如何处理DuplicateKeyException并同时保留所需的ModelAttributes?

问题描述 投票:0回答:1

我正在开发 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表单上的行为?预先感谢。

java spring postgresql
1个回答
0
投票

我无法使用带有

@ModelAttribute
注释的方法,因为我需要设备库存卡的值。

你错了,你可以只使用带有

@ModelAttribute
注释的方法,因为你也可以在其中使用
@PathVariable

@ModelAttribute
public void prepareModel(@PathVariable("inventoryCard") String inventoryCard, Model model) {
  model.addAttribute("acts", actDAO.showActsByDevice(inventoryCard));
}

这样就可以了。另请参阅文档

© www.soinside.com 2019 - 2024. All rights reserved.