Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a servlet instance

Tags:

java

servlets

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?

like image 969
anirvan Avatar asked Nov 01 '10 21:11

anirvan


People also ask

What is the instance of servlet?

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).

How many instances of a servlet are there in memory?

So, the correct statement would be there is only one instance per JVM for every servlet, unless it implements SingleThreadModel.

How are servlets invoked?

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.


1 Answers

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.

like image 95
BalusC Avatar answered Oct 11 '22 05:10

BalusC