使用@SessionAttributes时Thymeleaf POST后模型值不更新问题
问题解决方法
你的问题出在@SessionAttributes的属性同步时机:POST请求中添加到Model的属性,会在请求结束后才同步到会话,但当前视图渲染时会话中还没有该属性,所以Thymeleaf无法读取;刷新页面时GET请求会从会话加载属性到Model,因此能显示。
以下是两种无需刷新页面的解决方式:
方式一:同时操作Model和HttpSession
直接在POST方法中注入HttpSession,将属性同时存入会话和Model,确保当前视图渲染时能直接获取:
@Controller @SessionAttributes("myNewAttribute") public class SpringFileController { @GetMapping("/pageone") public String displayPageOne(Model model) { return "pageone"; } @PostMapping("/clickedsavebutton") public String handleSaveButton(Model model, HttpSession session){ String attrValue = "catnip"; // 同时存入会话和Model session.setAttribute("myNewAttribute", attrValue); model.addAttribute("myNewAttribute", attrValue); System.out.println(attrValue); return "pageone"; } }
方式二:使用@ModelAttribute注解预加载会话属性
在控制器中添加@ModelAttribute方法,提前将会话中的属性加载到Model,确保每次请求(包括POST)的视图都能获取到最新值:
@Controller @SessionAttributes("myNewAttribute") public class SpringFileController { // 预加载会话属性到Model @ModelAttribute("myNewAttribute") public String getMyNewAttribute(HttpSession session) { String attr = (String) session.getAttribute("myNewAttribute"); return attr != null ? attr : ""; } @GetMapping("/pageone") public String displayPageOne() { return "pageone"; } @PostMapping("/clickedsavebutton") public String handleSaveButton(Model model){ String attrValue = "catnip"; model.addAttribute("myNewAttribute", attrValue); System.out.println(attrValue); return "pageone"; } }
这两种方式都能让Thymeleaf在POST请求返回后立即显示myNewAttribute的值,同时保留页面其他修改内容。
内容的提问来源于stack exchange,提问作者skylight
相关产品推荐
相关产品推荐

