我认为您在这里寻找的是请求、会话或应用程序数据。
在 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");