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

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


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

有帮助吗?

解决方案

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

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

其他提示

将其放入3个不同范围之一。

请求 - 持续请求

会话 - 持续用户会话的生命

应用程序 - 持续到applciation关闭

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

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

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

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

另一种选择,在上下文之间共享数据......

share-data-between-servlets-on-tomcat

  <Context path="/myApp1" docBase="myApp1" crossContext="true"/>
  <Context path="/myApp2" docBase="myApp2" crossContext="true"/>

在myApp1上:

  ServletContext sc = getServletContext();
  sc.setAttribute("attribute", "value");

在myApp2上:

  ServletContext sc = getServletContext("/myApp1");
  String anwser = (String)sc.getAttribute("attribute");

难道你不能把对象放在HttpSession中,然后通过每个servlet中的属性名称来引用它吗?

e.g:

getSession().setAttribute("thing", object);

...然后在另一个servlet中:

Object obj = getSession.getAttribute("thing");

以下是我如何使用Jetty。

https://stackoverflow.com/a/46968645/1287091

使用服务器上下文,其中在嵌入式Jetty服务器启动期间写入单例,并在服务器生命周期内在所有Web应用程序之间共享。也可以用来在webapps之间共享对象/数据,假设上下文只有一个编写器 - 否则你需要注意并发。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top