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

查看:29
本文介绍了如何在两个或多个 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.

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

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

我想共享一个简单类的对象向量(只是公共属性、字符串、整数等).我的意图是像在数据库中一样拥有静态数据,显然当 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天全站免登陆