Start of Tutorial > Start of Trail > Start of Lesson | Search |
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 theServletContext
object'sgetServlet
method. Get theServletContext
object from theServletConfig
object stored in theServlet
object. An example should make this clear. When theBookDetail
servlet calls theBookDB
servlet, theBookDetail
servlet obtains theBookDB
servlet'sServlet
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 theBookDB
servlet'sgetBookDetails
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.
Start of Tutorial > Start of Trail > Start of Lesson | Search |