RedirectAttributes对象addFlashAttribute()的使用

本文介绍了 Spring MVC 中 RedirectAttributes 对象 addFlashAttribute() 方法及 ModelMap 对象 addAttribute() 方法的具体应用,通过示例展示了如何在编辑页面显示错误信息及验证失败时返回带有错误消息的视图。
  1. <span style=“font-size:14px;”>  
  2. </span>  
<span style="font-size:14px;">
</span>
  1. <strong><span style=“font-size:14px;”>RedirectAttributes对象addFlashAttribute()的使用</span></strong>  
<strong><span style="font-size:14px;">RedirectAttributes对象addFlashAttribute()的使用</span></strong>
  1. <span style=“font-size:14px;”><span style=“font-size:18px;”>@RequestMapping(value=“/edit/{id}”,method= RequestMethod.GET)  
  2.     public String edit(@PathVariable(value=“id”int id,ModelMap map,RedirectAttributes redirectAttributes) {  
  3.         PartsChange change = partsChangeService.findOne(id);  
  4.         PartsChangeFB fb = PartsChangeFB.toFB(change);  
  5.         if(!PartsChange.STATUS_NEW.equals(fb.getStatus())){  
  6.             redirectAttributes.addFlashAttribute(”errorInfo”,“不能修改!”);  
  7.             return “redirect:/partsChange”;  
  8.         }  
  9.         List<PartsChangeFile> fileList = partsChangeFileService.findByChangeId(id);  
  10.         map.addAttribute(”partsChange”, fb);  
  11.         map.addAttribute(”fileList”, fileList);  
  12.         return “partsChange/editInfo”;  
  13.     }</span></span>  
<span style="font-size:14px;"><span style="font-size:18px;">@RequestMapping(value="/edit/{id}",method= RequestMethod.GET)
    public String edit(@PathVariable(value="id") int id,ModelMap map,RedirectAttributes redirectAttributes) {
        PartsChange change = partsChangeService.findOne(id);
        PartsChangeFB fb = PartsChangeFB.toFB(change);
        if(!PartsChange.STATUS_NEW.equals(fb.getStatus())){
            redirectAttributes.addFlashAttribute("errorInfo","不能修改!");
            return "redirect:/partsChange";
        }
        List<PartsChangeFile> fileList = partsChangeFileService.findByChangeId(id);
        map.addAttribute("partsChange", fb);
        map.addAttribute("fileList", fileList);
        return "partsChange/editInfo";
    }</span></span>


ModelMap对象addAttribute()的使用

  1. <span style=“font-size:14px;”><span style=“font-size:14px;”>@RequestMapping(value = “/save”, method = RequestMethod.POST)  
  2.     public String save(@ModelAttribute @Valid EquipmentFB equipmentFB, BindingResult result, ModelMap map) {  
  3.         if (result.hasErrors()) {  
  4.             map.addAttribute(”message”, ErrorUtils.fetchAllErrorMessages(result));  
  5.             if(equipmentFB.getEquipTypeId() != null && equipmentFB.getEquipTypeId() != 0){  
  6.                 EquipType equipType = equipTypeService.findOne(equipmentFB.getEquipTypeId());  
  7.                 equipmentFB.setEquipTypeName(equipType.getName());  
  8.             }  
  9.             map.addAttribute(”equipment”, equipmentFB);  
  10.             return “/nbs/equipment/edit”;  
  11.         }  
  12.         String error = ”“;  
  13.           
  14.         if(StringUtils.isEmpty(equipmentFB.getNumber())){  
  15.             error = error +Constant.ERROR_EQUIPMENTCONTROLLER_NUMBER_CANNOT_NULL;  
  16.         }  
  17.           
  18.         if(StringUtils.isEmpty(equipmentFB.getName())){  
  19.             error = error +Constant.ERROR_EQUIPMENTCONTROLLER_NAME_CANNOT_NULL;  
  20.         }  
  21.           
  22.         if(equipmentFB.getEquipTypeId() == null || equipmentFB.getEquipTypeId() == 0){  
  23.             error = error +Constant.ERROR_EQUIPMENTCONTROLLER_TYPE_CANNOT_NULL;  
  24.         }  
  25.         if (!“”.equals(error)) {  
  26.             map.addAttribute(”message”, error);  
  27.             if(equipmentFB.getEquipTypeId() != null && equipmentFB.getEquipTypeId() != 0){  
  28.                 EquipType equipType = equipTypeService.findOne(equipmentFB.getEquipTypeId());  
  29.                 equipmentFB.setEquipTypeName(equipType.getName());  
  30.             }  
  31.             map.addAttribute(”equipment”, equipmentFB);  
  32.             return “/nbs/equipment/edit”;  
  33.         }  
  34.   
  35.         Equipment equipment = new Equipment();  
  36.         if (equipmentFB.getId() != null) {  
  37.             equipment = equipmentService.getEquipment(equipmentFB.getId());  
  38.             // machineFB.setVersion(machineEntity.getVersion());//修改时不获得版本号,copy时会报错  
  39.         }  
  40.         BeanUtils.copyProperties(equipmentFB, equipment);  
  41.         if (equipmentFB.getEquipTypeId() != null && equipmentFB.getEquipTypeId() != 0) {  
  42.             equipment.setEquipType(equipTypeService.getEquipType(equipmentFB.getEquipTypeId()));  
  43.         }  
  44.         try {  
  45.             equipmentService.save(equipment);  
  46.         } catch (DataIntegrityViolationException e) {  
  47.             map.addAttribute(”message”, Constant.MESSAGE_EQUIPMENTCONTROLLER_NUMBER_EXEIT);  
  48.             if(equipmentFB.getEquipTypeId() != null && equipmentFB.getEquipTypeId() != 0){  
  49.                 EquipType equipType = equipTypeService.findOne(equipmentFB.getEquipTypeId());  
  50.                 equipmentFB.setEquipTypeName(equipType.getName());  
  51.             }  
  52.             map.addAttribute(”equipment”, equipmentFB);  
  53.             return “/nbs/equipment/edit”;  
  54.         }  
  55.         return “redirect:/nbs/equipment”;  
  56.   
  57.     }</span></span>  
<span style="font-size:14px;"><span style="font-size:14px;">@RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(@ModelAttribute @Valid EquipmentFB equipmentFB, BindingResult result, ModelMap map) {
        if (result.hasErrors()) {
            map.addAttribute("message", ErrorUtils.fetchAllErrorMessages(result));
            if(equipmentFB.getEquipTypeId() != null && equipmentFB.getEquipTypeId() != 0){
                EquipType equipType = equipTypeService.findOne(equipmentFB.getEquipTypeId());
                equipmentFB.setEquipTypeName(equipType.getName());
            }
            map.addAttribute("equipment", equipmentFB);
            return "/nbs/equipment/edit";
        }
        String error = "";

        if(StringUtils.isEmpty(equipmentFB.getNumber())){
            error = error +Constant.ERROR_EQUIPMENTCONTROLLER_NUMBER_CANNOT_NULL;
        }

        if(StringUtils.isEmpty(equipmentFB.getName())){
            error = error +Constant.ERROR_EQUIPMENTCONTROLLER_NAME_CANNOT_NULL;
        }

        if(equipmentFB.getEquipTypeId() == null || equipmentFB.getEquipTypeId() == 0){
            error = error +Constant.ERROR_EQUIPMENTCONTROLLER_TYPE_CANNOT_NULL;
        }
        if (!"".equals(error)) {
            map.addAttribute("message", error);
            if(equipmentFB.getEquipTypeId() != null && equipmentFB.getEquipTypeId() != 0){
                EquipType equipType = equipTypeService.findOne(equipmentFB.getEquipTypeId());
                equipmentFB.setEquipTypeName(equipType.getName());
            }
            map.addAttribute("equipment", equipmentFB);
            return "/nbs/equipment/edit";
        }

        Equipment equipment = new Equipment();
        if (equipmentFB.getId() != null) {
            equipment = equipmentService.getEquipment(equipmentFB.getId());
            // machineFB.setVersion(machineEntity.getVersion());//修改时不获得版本号,copy时会报错
        }
        BeanUtils.copyProperties(equipmentFB, equipment);
        if (equipmentFB.getEquipTypeId() != null && equipmentFB.getEquipTypeId() != 0) {
            equipment.setEquipType(equipTypeService.getEquipType(equipmentFB.getEquipTypeId()));
        }
        try {
            equipmentService.save(equipment);
        } catch (DataIntegrityViolationException e) {
            map.addAttribute("message", Constant.MESSAGE_EQUIPMENTCONTROLLER_NUMBER_EXEIT);
            if(equipmentFB.getEquipTypeId() != null && equipmentFB.getEquipTypeId() != 0){
                EquipType equipType = equipTypeService.findOne(equipmentFB.getEquipTypeId());
                equipmentFB.setEquipTypeName(equipType.getName());
            }
            map.addAttribute("equipment", equipmentFB);
            return "/nbs/equipment/edit";
        }
        return "redirect:/nbs/equipment";

    }</span></span>


@RequestMapping("/savePet") public String savePet(Pet pet, @RequestParam(value = "file", required = false) MultipartFile file, RedirectAttributes redirectAttributes) { try { // 如果是编辑操作,先获取原有宠物信息 Pet existingPet = null; if (pet.getId() != null) { existingPet = petService.getPetById(pet.getId()); } if (file != null && !file.isEmpty()) { // 处理文件上传 String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename(); String uploadDir = "D:/uploads/"; File dir = new File(uploadDir); if (!dir.exists()) { dir.mkdirs(); } String filePath = uploadDir + fileName; // 保存文件到服务器 file.transferTo(new File(filePath)); // 设置图片路径到 pet 对象 - 使用相对路径 pet.setPic("/uploads/" + fileName); // 如果编辑时有新文件上传,删除旧图片(可选) if (existingPet != null && existingPet.getPic() != null) { deleteOldImage(existingPet.getPic()); } } else if (existingPet != null) { // 如果没有上传新文件,保持原有图片 pet.setPic(existingPet.getPic()); } // 设置默认状态 if (pet.getPetstatus() == null) { pet.setPetstatus(0); } // 执行数据库操作 if (pet.getId() == null) { petService.addPet(pet); redirectAttributes.addFlashAttribute("message", "宠物添加成功"); } else { petService.updatePet(pet); redirectAttributes.addFlashAttribute("message", "宠物信息更新成功"); } } catch (IOException e) { redirectAttributes.addFlashAttribute("errorMessage", "文件上传失败: " + e.getMessage()); return "redirect:/admin/pet"; } catch (Exception e) { redirectAttributes.addFlashAttribute("errorMessage", "操作失败: " + e.getMessage()); return "redirect:/admin/pet"; } return "redirect:/admin/pet"; }使用该controler时,pic不显示, <c:if test="${not empty pet.pic}"> <img th:if="${pet.pic}" th:src="@{${pet.pic}}" alt="宠物图片" style="width: 100px; height: 100px; object-fit: cover;"> </c:if> <c:if test="${empty pet.pic}"> 无图片 </c:if>解决
最新发布
10-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值