Java 如何在两个或多个 Servlet 之间共享变量或对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/123657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I share a variable or object between two or more Servlets?
提问by David Ameller
I would like to know if there is some way to share a variable or an object between two or more Servlets, I mean some "standard" way. I suppose that this is not a good practice but is a easier way to build a prototype.
我想知道是否有某种方法可以在两个或多个 Servlet 之间共享变量或对象,我的意思是某种“标准”方式。我想这不是一个好的做法,而是构建原型的一种更简单的方法。
I don't know if it depends on the technologies used, but I'll use Tomcat 5.5
我不知道这是否取决于所使用的技术,但我将使用 Tomcat 5.5
I want to share a Vector of objects of a simple class (just public attributes, strings, ints, etc). My intention is to have a static data like in a DB, obviously it will be lost when the Tomcat is stopped. (it's just for Testing)
我想共享一个简单类的对象向量(只是公共属性、字符串、整数等)。我的目的是像在数据库中一样拥有静态数据,显然当 Tomcat 停止时它会丢失。(仅用于测试)
采纳答案by William
I think what you're looking for here is request, session or application data.
我认为您在这里寻找的是请求、会话或应用程序数据。
In a servlet you can add an object as an attribute to the request object, session object or servlet context object:
在 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);
}
If you put it in the request object it will be available to the servlet that is forwarded to until the request is finished:
如果你把它放在请求对象中,它将对转发到的 servlet 可用,直到请求完成:
request.getAttribute("sharedId");
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:
如果您将它放在会话中,它将对所有 servlet 可用,但该值将与用户相关联:
request.getSession().getAttribute("sharedId");
Until the session expires based on inactivity from the user.
直到会话基于用户的不活动而过期。
Is reset by you:
由您重置:
request.getSession().invalidate();
Or one servlet removes it from scope:
或者一个 servlet 将其从作用域中移除:
request.getSession().removeAttribute("sharedId");
If you put it in the servlet context it will be available while the application is running:
如果将它放在 servlet 上下文中,它将在应用程序运行时可用:
this.getServletConfig().getServletContext().getAttribute("sharedId");
Until you remove it:
直到你删除它:
this.getServletConfig().getServletContext().removeAttribute("sharedId");
回答by yalestar
Couldn't you just put the object in the HttpSession and then refer to it by its attribute name in each of the servlets?
难道您不能将对象放在 HttpSession 中,然后在每个 servlet 中通过其属性名称来引用它吗?
e.g:
例如:
getSession().setAttribute("thing", object);
...then in another servlet:
...然后在另一个 servlet 中:
Object obj = getSession.getAttribute("thing");
回答by shemnon
Depends on the scope of the intended use of the data.
取决于数据的预期用途范围。
If the data is only used on a per-user basis, like user login info, page hit count, etc. use the session object (httpServletRequest.getSession().get/setAttribute(String [,Object]))
如果数据仅在每个用户的基础上使用,例如用户登录信息、页面命中计数等,请使用会话对象 (httpServletRequest.getSession().get/setAttribute(String [,Object]))
If it is the same data across multiple users (total web page hits, worker threads, etc) use the ServletContext attributes. servlet.getServletCongfig().getServletContext().get/setAttribute(String [,Object])). This will only work within the same war file/web applicaiton. Note that this data is not persisted across restarts either.
如果它是跨多个用户的相同数据(网页点击总数、工作线程等),请使用 ServletContext 属性。servlet.getServletCongfig().getServletContext().get/setAttribute(String [,Object]))。这仅适用于同一个战争文件/网络应用程序。请注意,此数据也不会在重新启动后保持不变。
回答by bpapa
Put it in one of the 3 different scopes.
把它放在 3 个不同的范围之一。
request - lasts life of request
request - 持续请求的生命周期
session - lasts life of user's session
session - 持续用户会话的生命周期
application - lasts until applciation is shut down
应用程序 - 持续到应用程序关闭
You can access all of these scopes via the HttpServletRequest variable that is passed in to the methods that extend from the HttpServlet class
您可以通过传递给从HttpServlet 类扩展的方法的 HttpServletRequest 变量访问所有这些范围
回答by ggrandes
Another option, share data betwheen contexts...
另一种选择,在上下文之间共享数据......
share-data-between-servlets-on-tomcat
<Context path="/myApp1" docBase="myApp1" crossContext="true"/>
<Context path="/myApp2" docBase="myApp2" crossContext="true"/>
On myApp1:
在 myApp1 上:
ServletContext sc = getServletContext();
sc.setAttribute("attribute", "value");
On myApp2:
在 myApp2 上:
ServletContext sc = getServletContext("/myApp1");
String anwser = (String)sc.getAttribute("attribute");
回答by Reed Sandberg
Here's how I do this with Jetty.
这是我如何使用 Jetty 执行此操作。
https://stackoverflow.com/a/46968645/1287091
https://stackoverflow.com/a/46968645/1287091
Uses the server context, where a singleton is written to during startup of an embedded Jetty server and shared among all webapps for the life of the server. Can also be used to share objects/data between webapps assuming there is only one writer to the context - otherwise you need to be mindful of concurrency.
使用服务器上下文,在嵌入式 Jetty 服务器启动期间写入一个单例,并在服务器的生命周期内在所有 web 应用程序之间共享。也可用于在 web 应用程序之间共享对象/数据,假设上下文只有一个编写者 - 否则您需要注意并发性。