且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-08 22:40:52

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

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