如何从一个 servlet 访问另一个 servlet 中创建的对象
我有一个问题。假设有 2 个 servlet:Load() 和 Process()。在 Load() 期间,我想创建并初始化一些对象。在 Process() 期间,我想将这些对象用于其他一些事情。
由于 servlet 中没有主类(与桌面编程相反),因此我认为我无法返回由 Load() 创建的对象并将其作为参数从主类传递给 Process() 。
那么,如何在一个 servlet 调用期间创建一个对象并从其他 servlet 使用/访问该对象呢?
I have a problem. Lets say there are 2 servlets: Load() and Process(). During Load(), I want to create and initialize some objects. and During Process(), I want to use those objects for some other things.
Since there is no main class in a servlet (as opposed to desktop programming), I don't think that I can return object created by Load() and pass it as argument to Process() from the main class.
So, how could I create an object in during one servlet call and use/access that object from other servlet?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
ServletContext
:getServletContext().setAttribute(..)
另外,请考虑将初始化代码和处理代码放在一个 servlet 中。如果其中一个只有
init()
,而另一个则有doGet()
,并且这些对象应该仅在这两个 servlet 之间共享,则没有这种分离的点。更新:如果您想在同一用户的连续请求中重用对象(即不要将它们初始化一次并在各处使用它们),而不是将它们放入
ServletContext
中,将它们放在较小的范围内 -HttpSession
(通过request.getSession()
获得)Use the
ServletContext
:getServletContext().setAttribute(..)
Also, consider placing the initialization code and the processing code in one servlet. If you are only having
init()
in one of them, anddoGet()
in the other, and these objects should be shared only between these two servlets, there is no point of this separation.Update: if you want to reuse objects in successive requests by the same user (i.e. not initialize them once and use them everywhere), than instead of putting them in the
ServletContext
, put them in a smaller scope - theHttpSession
(obtained byrequest.getSession()
)不确定我理解 Load() 和 Process() 的意思。 Servlet 不是函数。它们被映射到某个 URL 及其 service() 函数由 servlet 容器调用。可以将多个 servlet 映射到一个 URL,并按照 web.xml 中定义的顺序调用它们。
要回答您的问题:状态通常通过 setAttribute()
您可以通过 getAttribute() 在其他 Servlet 中访问它。
Not sure i understand what you mean with Load() and Process(). Servlets are no functions. They are mapped to a certain URL and their service() funktion gets called by the servlet container. More than one servlet can be mapped to an URL and they are called in the order they are defined in the web.xml.
To anser your question: state is normaly stored the the Session object via setAttribute()
You can than access it in the other Servlet via getAttribute().