anirvan
anirvan

Reputation: 4877

Accessing a servlet instance

while i can't really think of a practical use-case for such a scenario, but i purely intend this to be a curiosity driven question.

i understand the servlet container holds onto all the instances created of the servlets, and delegates request threads to these instances. it also makes sense to keep these instances managed, to avoid unwarranted calls to alter the lifecycle of servlet instances outside the purview of the container.

but is there really no way to access the servlet instances?

Upvotes: 9

Views: 6020

Answers (3)

BalusC
BalusC

Reputation: 1108632

Prior to Servlet 2.1 (over a decade old already), you could use ServletContext#getServlet() for this. It's however deprecated since then. Simply because it's a bad design. If you want to invoke another servlet from inside a servlet in the request-response chain, just use RequestDispatcher#include(). If you want to invoke non-servlet specific methods of another servlet, then it's simply high time to refactor that code into a separate Java class which you could then import/use in the both servlets.

Upvotes: 6

Not through the standard Servlet API (so the answer is no).

You may, however, use your knowledge of the actual implementation and nasty tricks with reflection to get hold of the data structure used by the implementation to hold servlet instances, (so the answer is yes).

The servlet container may, however, have a SecurityManager in place prohibiting using said nasty tricks (so the answer is maybe).

Upvotes: 0

Aravind Yarram
Aravind Yarram

Reputation: 80166

The container creates ONLY ONE instance of the Servlet and uses the same instance to serve multiple requests. There is "SingleThreadModel" which if you implement, container would create multiple instances of the Servlet but that is deprecated now.

Upvotes: 2

Related Questions