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

我想知道是否有某种方式可以在两个或多个Servlet之间共享变量或对象,我的意思是某种“标准”方式。我认为这不是一个好习惯,但是是构建原型的更简单方法。

我不知道这是否取决于所使用的技术,但我将使用Tomcat 5.5


我想共享一个简单类的对象的Vector(仅公共属性,字符串,int等)。我的意图是在数据库中拥有一个静态数据,当Tomcat停止时,它显然会丢失。(仅用于测试)

回答:

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

在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");

以上是 如何在两个或多个Servlet之间共享变量或对象? 的全部内容, 来源链接: utcz.com/qa/412797.html

回到顶部