You need to enable JavaScript to run this app. 如何让Spring MVC中一个Handler设置的变量在另一个Handler中可访问?
优惠活动
大模型
产品
解决方案
定价
更多

如何让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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 23:36:03