如何让Spring MVC中一个Handler设置的变量在另一个Handler中可访问?
问题原因
重定向本质是服务端返回302状态码让浏览器发起新的GET请求,每个请求的Model是独立的上下文,只会在当前请求的视图渲染阶段生效,跨请求自然无法共享。你用Controller类字段存储的方式存在严重并发问题:Spring Controller默认是单例,类字段会被所有用户请求共享,多用户同时操作时会出现消息串扰的故障,绝对不能使用。
标准解决方案:使用RedirectAttributes传递重定向参数
这是Spring MVC原生提供的重定向传参机制,和Thymeleaf无关,你现有的Thymeleaf渲染代码不需要做任何修改。
步骤1:修改PostMapping接口参数
将原方法中的Model参数替换为RedirectAttributes,使用addFlashAttribute方法存储stopMessage:
import org.springframework.web.servlet.mvc.support.RedirectAttributes; @PostMapping("/auto-upgrade/stop") public String stopJob(@ModelAttribute StopRequest stopRequest, RedirectAttributes redirectAttributes) { try { //something that may fail redirectAttributes.addFlashAttribute("stopMessage", "Stop request accepted"); } catch (UpgradeNotRunningException | NotInGracePeriodException | StopUpgradeException e) { redirectAttributes.addFlashAttribute("stopMessage", "FAILED TO STOP: " + e.getMessage()); } return "redirect:/auto-upgrade/" + stopRequest.getJobId(); }
步骤2:无需修改现有GetMapping逻辑
通过addFlashAttribute存储的属性会临时保存在用户Session中,重定向到目标GetMapping接口时,Spring会自动将该属性注入到GetMapping的Model中,你原有的判断逻辑、Thymeleaf渲染代码都可以直接复用,不需要调整。
特性说明
- Flash属性仅会在重定向后的第一次请求中生效,读取后自动清除,不会残留在Session中污染后续请求
- 线程安全,每个用户的Flash属性独立存储,不会出现多用户串数据的问题
内容的提问来源于stack exchange,提问作者Matteo NNZ
相关产品推荐
相关产品推荐

