The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search

Trail: Servlets
Lesson: Servlet Communication

Calling Servlets from Servlets

To have your servlet call another servlet, you can either:

This section addresses the second option. To call another servlet's public methods directly, you must:

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.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search