栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将通知消息设置为请求属性,该属性应在sendRedirect之后显示

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将通知消息设置为请求属性,该属性应在sendRedirect之后显示

您正在寻找“ Flash作用域 ”。

闪存作用域由一个短暂的cookie支持,该cookie与会话作用域中的数据条目相关联。重定向之前,将在HTTP响应上设置一个cookie,该cookie的值与会话范围内的数据条目唯一关联。重定向之后,将检查Flash作用域cookie的存在,并将与cookie关联的数据条目从会话作用域中删除,并将其放入重定向请求的请求作用域中。最后,cookie将从HTTP响应中删除。这样,重定向的请求可以访问在初始请求中准备的请求范围的数据。

用简单的Servlet术语表示如下:

  1. 创建闪存作用域并添加条目:
        String message = "Some message";    // ...    Map<String, Object> flashScope = new HashMap<>();    flashScope.put("message", message);
  1. 重定向之前,请将其存储在以唯一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");
  1. 在下一个请求中,找到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过滤器)进一步抽象该方法。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/421988.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号