重定向后FlashAttributes未出现在Model中的问题排查
这个问题我之前在项目里也碰到过,咱们从几个常见的排查点入手,一步步解决:
1. 先确认你是否主动添加了Flash属性
看你贴的删除方法代码,try块里只做了删除操作,没看到添加Flash属性的代码!这是最容易忽略的点——Spring不会自动帮你添加Flash属性,得你手动调用redirectAttributes.addFlashAttribute()方法才行。比如删除成功/失败时分别添加提示信息:
@GetMapping(value = "/notations/delete") public String delete(@RequestParam(name="id", required=true) Long id, RedirectAttributes redirectAttributes) { try { notationRepository.deleteById(id); // 添加成功提示的Flash属性 redirectAttributes.addFlashAttribute("successMsg", "标注删除成功!"); } catch (RuntimeException e) { // 添加失败提示的Flash属性 redirectAttributes.addFlashAttribute("errorMsg", "删除失败:" + e.getMessage()); } // 确保重定向到列表页 return "redirect:/notations"; }
2. 检查重定向目标页面是否正确读取属性
你的列表方法listAll已经把notations放到Model里了,Spring会自动把Flash属性同步到目标方法的Model中,但要确保前端页面能正确获取这些属性。比如用Thymeleaf的话,页面里要这么写:
<!-- 显示成功信息 --> <div th:if="${successMsg}" class="alert alert-success" th:text="${successMsg}"></div> <!-- 显示错误信息 --> <div th:if="${errorMsg}" class="alert alert-danger" th:text="${errorMsg}"></div>
如果是JSP,就用${successMsg}这种EL表达式读取就行。
3. 确认重定向语法是否正确
要保证删除方法的返回值是带redirect:前缀的路径,比如return "redirect:/notations"——只有这样Spring才会识别这是重定向请求,进而处理FlashAttributes。如果返回的是普通视图名(比如直接返回"supply/notations"),那就是转发而不是重定向,Flash属性的逻辑不会生效。
4. 排查是否有拦截器/过滤器干扰
如果你的项目里有自定义的拦截器或者过滤器,可能会在请求传递过程中清空了Flash相关的属性。可以先临时禁用这些自定义组件,测试删除重定向后Flash属性是否正常显示。如果恢复正常,再去检查拦截器/过滤器的代码,确保没有修改或清除FlashMap相关的内容。
5. 老版本Spring的配置问题(较少见)
如果是Spring MVC 4.x之前的老项目,可能需要手动配置FlashMapManager或者确保RequestDataValueProcessor正确初始化。不过现在Spring Boot项目默认都已经配置好了,这个情况概率比较低,但如果是维护老项目可以排查一下。
内容的提问来源于stack exchange,提问作者hooch

