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

Dav*_*ler 41 java servlets web-applications

我想知道是否有一些方法可以在两个或更多Servlet之间共享变量或对象,我的意思是一些"标准"方式.我认为这不是一个好习惯,但是构建原型是一种更简单的方法.

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


我想分享一个简单类的对象的Vector(只是公共属性,字符串,整数等).我的目的是拥有像DB一样的静态数据,显然它会在Tomcat停止时丢失.(它只是用于测试)

Wil*_*iam 78

我想你在这里寻找的是请求,会话或应用程序数据.

在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);
}
Run Code Online (Sandbox Code Playgroud)

如果将它放在请求对象中,它将被转发到的servlet可用,直到请求完成:

request.getAttribute("sharedId");
Run Code Online (Sandbox Code Playgroud)

如果你把它放在会话中,它将可用于所有servlet,但是值将与用户绑定:

request.getSession().getAttribute("sharedId");
Run Code Online (Sandbox Code Playgroud)

直到会话根据用户的不活动而到期.

由您重置:

request.getSession().invalidate();
Run Code Online (Sandbox Code Playgroud)

或者一个servlet将其从范围中删除:

request.getSession().removeAttribute("sharedId");
Run Code Online (Sandbox Code Playgroud)

如果将它放在servlet上下文中,它将在应用程序运行时可用:

this.getServletConfig().getServletContext().getAttribute("sharedId");
Run Code Online (Sandbox Code Playgroud)

直到你删除它:

this.getServletConfig().getServletContext().removeAttribute("sharedId");
Run Code Online (Sandbox Code Playgroud)


bpa*_*apa 9

把它放在3个不同的范围之一.

请求 - 持续请求

session - 持续用户会话的生命

应用程序 - 持续到applciation关闭

您可以通过HttpServletRequest变量访问所有这些范围,该变量传递给从HttpServlet类扩展的方法


she*_*non 7

取决于数据的预期用途范围.

如果数据仅用于每个用户,如用户登录信息,页面命中计数等,请使用会话对象(httpServletRequest.getSession().get/setAttribute(String [,Object]))

如果跨多个用户(总网页命中,工作线程等)的数据相同,则使用ServletContext属性.servlet.getServletCongfig().getServletContext().get/setAttribute(String [,Object])).这只适用于同一个war文件/ web应用程序.请注意,此数据也不会在重新启动时保留.