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?
When a single-threaded servlet is deployed to the Sun Java System Web Server, the servlet engine creates a servlet instance pool used for incoming requests (multiple copies of the same servlet in memory).
So, the correct statement would be there is only one instance per JVM for every servlet, unless it implements SingleThreadModel.
A servlet is typically invoked via a servlet mapping in your servlet container configuration, when a request is made to the servlet container for a path matching that mapping. There are a number of resources for learning more about servlets on the Sun Oracle Java site's servlet page.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With