且构网

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

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

更新时间:2023-11-08 22:49:28

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

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