Servlet Reuse
Another use for interservlet communication is to allow one servlet to reuse the abilities (the public methods) of another servlet. The major challenge with servlet reuse is for the “user” servlet to obtain the proper instance of “usee” servlet when the usee servlet has not yet been loaded into the server.
The obvious solutions don’t always work.
getServlet() isn’t guaranteed to load the
named servlet on all servers; it may just return
null. Directly creating a new instance of the usee
servlet doesn’t work either, as the newly created servlet
doesn’t have access to its own ServletConfig
and ServletContext objects. Plus, the server would
be using a different instance to handle client requests, leaving the
new instance of the servlet without the right state information.
The solution is for the user servlet to ask the server to load the
usee servlet, then call getServlet() to get a
reference to it. Unfortunately, the Servlet API distinctly lacks any
methods whereby a servlet can control the servlet life cycle, for
itself or for other servlets. This is considered a security risk and
is officially “left for future consideration.”
Fortunately, there’s a back door we can use today. A servlet
can open an HTTP connection to the server in which it’s
running, ask for the unloaded servlet, and effectively force the
server to load the servlet to handle the request. Then a call to
getServlet() gets the proper instance.[44]
An Improved getServlet()
The com.oreilly.servlet.ServletUtils ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access