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