First, identify which servlet to call by specifying a URI. This is normally a path relative to the current application. For example, if your servlet is part of an application with a context root called OfficeFrontEnd, the URL to a servlet called ShowSupplies from a browser is as follows:
http://server:port/OfficeApp/OfficeFrontEnd/servlet/ShowSupplies?name=value
You can call this servlet programmatically from another servlet in one of two ways, as described below.
To include another servlet's output, use the include() method from the RequestDispatcher interface. This method calls a servlet by its URI and waits for it to return before continuing to process the interaction. The include() method can be called multiple times within a given servlet.
For example:
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/ShowSupplies"); dispatcher.include(request, response); |
To hand interaction control to another servlet, use the RequestDispatcher interface's forward() method with the servlet's URI as a parameter.
This example shows a servlet using forward():
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/ShowSupplies"); dispatcher.forward(request, response); |