如何在两个或多个Servlet之间共享变量或对象? [英] How can I share a variable or object between two or more Servlets?

查看:1046
本文介绍了如何在两个或多个Servlet之间共享变量或对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to know if there is some way to share a variable or an object between two or more Servlets, I mean some "standard" way. I suppose that this is not a good practice but is a easier way to build a prototype.

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

I don't know if it depends on the technologies used, but I'll use Tomcat 5.5

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

I want to share a Vector of objects of a simple class (just public attributes, strings, ints, etc). My intention is to have a static data like in a DB, obviously it will be lost when the Tomcat is stopped. (it's just for Testing)

推荐答案

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

I think what you're looking for here is request, session or application data.

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

In a servlet you can add an object as an attribute to the request object, session object or servlet context object:

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使用被转发到请求完成:

If you put it in the request object it will be available to the servlet that is forwarded to until the request is finished:

request.getAttribute("sharedId");

如果你把它放在会话中,它将可用于所有servlet,但值将会绑定到用户:

If you put it in the session it will be available to all the servlets going forward but the value will be tied to the user:

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

根据用户的不活动情况,会话到期为止。

Until the session expires based on inactivity from the user.

由您重置:

request.getSession().invalidate();

或者一个servlet将其从范围中移除:

Or one servlet removes it from scope:

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

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

If you put it in the servlet context it will be available while the application is running:

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

直到你删除它:

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

这篇关于如何在两个或多个Servlet之间共享变量或对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆