您正在寻找“ Flash作用域 ”。
闪存作用域由一个短暂的cookie支持,该cookie与会话作用域中的数据条目相关联。重定向之前,将在HTTP响应上设置一个cookie,该cookie的值与会话范围内的数据条目唯一关联。重定向之后,将检查Flash作用域cookie的存在,并将与cookie关联的数据条目从会话作用域中删除,并将其放入重定向请求的请求作用域中。最后,cookie将从HTTP响应中删除。这样,重定向的请求可以访问在初始请求中准备的请求范围的数据。
用简单的Servlet术语表示如下:
- 创建闪存作用域并添加条目:
String message = "Some message"; // ... Map<String, Object> flashScope = new HashMap<>(); flashScope.put("message", message);- 重定向之前,请将其存储在以唯一ID为键的会话中,并将其设置为cookie:
String flashScopeId = UUID.randomUUID().toString(); request.getSession().setAttribute(flashScopeId, flashScope); cookie cookie = new cookie("flash", flashScopeId); cookie.setPath(request.getContextPath()); response.addcookie(cookie); // ... response.sendRedirect(request.getContextPath() + "/someservlet");- 在下一个请求中,找到Flash cookie,将其映射回请求范围并删除cookie:
if (request.getcookies() != null) { for (cookie cookie : request.getcookies()) { if ("flash".equals(cookie.getName())) { Map<String, Object> flashScope = (Map<String, Object>) request.getSession().getAttribute(cookie.getValue()); if (flashScope != null) { request.getSession().removeAttribute(cookie.getValue()); for (Entry<String, Object> entry : flashScope.entrySet()) { request.setAttribute(entry.getKey(), entry.getValue()); } } cookie.setValue(null); cookie.setMaxAge(0); cookie.setPath(request.getContextPath()); response.addcookie(cookie); } } }可以使用特定于上下文的帮助器方法(例如
setFlashAttribute(),带有响应包装器的Servlet过滤器)进一步抽象该方法。



