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

如何在两个或多个Servlet之间共享变量或对象?

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

如何在两个或多个Servlet之间共享变量或对象?

我认为您在这里寻找的是请求,会话或应用程序数据。

在servlet中,您可以将对象作为属性添加到请求对象,会话对象或servlet上下文对象中:

protected void doGet(HttpServletRequest request, HttpServletResponse response) {    String shared = "shared";    request.setAttribute("sharedId", shared); // add to request    request.getSession().setAttribute("sharedId", shared); // add to session    this.getServletConfig().getServletContext().setAttribute("sharedId", shared); // add to application context    request.getRequestDispatcher("/URLofOtherServlet").forward(request, response);}

如果将其放在请求对象中,它将对转发到的Servlet可用,直到请求完成:

request.getAttribute("sharedId");

如果将其放在会话中,则以后的所有servlet都可以使用它,但是该值将绑定到用户:

request.getSession().getAttribute("sharedId");

直到会话过期为止(基于用户的不活动状态)。

由您重置:

request.getSession().invalidate();

或者一个servlet从范围中删除它:

request.getSession().removeAttribute("sharedId");

如果将其放在servlet上下文中,则在应用程序运行时将可用:

this.getServletConfig().getServletContext().getAttribute("sharedId");

直到将其删除:

this.getServletConfig().getServletContext().removeAttribute("sharedId");


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

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

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