Calling Servlets from Servlets
To have your servlet call another servlet, you can either:
- A servlet can make an HTTP request of another servlet. Opening a
connection to a URL is discussed in the Working with URLs lesson in
this tutorial.
- A servlet can call another servlet's public methods directly, if the
two servlets run within the same server.
This section addresses the second option. To call another servlet's
public methods directly, you must:
- Know the name of the
servlet that you want to call.
- Gain access to that servlet's
Servlet object
- Call the servlet's public method
To gain access to the Servlet object, use the
ServletContext object's getServlet method. Get
the ServletContext object from the ServletConfig
object stored in the Servlet object. An example should make
this clear. When the BookDetail servlet calls the
BookDB servlet, the BookDetail servlet obtains
the BookDB servlet's Servlet object like this:
public class BookDetailServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
...
BookDBServlet database = (BookDBServlet)
getServletConfig().getServletContext().getServlet("bookdb");
...
}
}
Once you have the servlet object, you can call any of that servlet's
public methods. For example, the BookDetail servlet
calls the BookDB servlet's getBookDetails method:
public class BookDetailServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
...
BookDBServlet database = (BookDBServlet)
getServletConfig().getServletContext().getServlet("bookdb");
BookDetails bd = database.getBookDetails(bookId);
...
}
}
You must exercise caution when you call another servlet's methods. If
the servlet that you want to call implements the SingleThreadModel interface, your call could violate the
called servlet's single threaded nature. (The server has no way to
intervene and make sure your call happens when the servlet is not
interacting with another client.) In this case, your servlet should make
an HTTP request of the other servlet instead of calling the other servlet's
methods directly.
|