|
|
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
Servletobject
- Call the servlet's public method
To gain access to the
Servletobject, use theServletContextobject'sgetServletmethod. Get theServletContextobject from theServletConfigobject stored in theServletobject. An example should make this clear. When theBookDetailservlet calls theBookDBservlet, theBookDetailservlet obtains theBookDBservlet'sServletobject 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
BookDetailservlet calls theBookDBservlet'sgetBookDetailsmethod: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
SingleThreadModelinterface, 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 |