如何通过Spring RedirectStrategy传播FlashMap属性?解决FlashMessage无法访问问题
问题原因与解决方法
你当前的问题出在错误使用FlashMap方法,以及缺少FlashMap的手动保存步骤:
1. 错误的方法调用
addTargetRequestParam()的作用是给重定向URL添加查询参数(最终会跳转到/secrets?message=xxx),而非将数据存入Flash属性中。这就是你在Thymeleaf里无法通过${message}访问内容的核心原因。
2. 缺少FlashMap的手动保存
在Controller以外的组件(比如你的AuthenticationFailureHandler)操作FlashMap时,Spring不会自动将FlashMap保存到会话中,需要手动调用FlashMapManager完成保存。
修正后的代码
import org.springframework.web.servlet.FlashMap; import org.springframework.web.servlet.FlashMapManager; import org.springframework.web.servlet.support.RequestContextUtils; public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler { private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); @Override public void onAuthenticationFailure( HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException { // 获取FlashMap对象 FlashMap outputFlashMap = RequestContextUtils.getOutputFlashMap(request); if (outputFlashMap != null) { // 使用put方法添加Flash属性(替代addTargetRequestParam) outputFlashMap.put("message", "Elvis says Aloha from Hawaii"); // 获取FlashMapManager并手动保存FlashMap FlashMapManager flashMapManager = RequestContextUtils.getFlashMapManager(request); if (flashMapManager != null) { flashMapManager.saveOutputFlashMap(outputFlashMap, request, response); } } redirectStrategy.sendRedirect(request, response, "/secrets"); } }
Thymeleaf访问方式
修正后,直接在Thymeleaf模板中使用${message}即可访问Flash属性,无需通过#request.getAttribute()。
额外注意事项
- 确保
/secrets对应的Controller方法是GET请求,Flash属性仅在重定向后的第一个GET请求中有效。 - 确认Spring Security配置中已正确注册这个
CustomAuthenticationFailureHandler。
内容的提问来源于stack exchange,提问作者Slevin
相关产品推荐
相关产品推荐

