You can invoke a servlet by directly addressing it from a Web page with a URL or by calling it programmatically from an already running servlet, as described in the following sections:
You can call servlets by using URLs embedded as links in HTML or JSP pages. The format of these URLs is as follows:
http://server:port/context_root/servlet/servlet_name?name=value
The following table describes each URL section. The left column lists the URL elements, and the right column lists descriptions of each URL element.
Table 2–1 URL Fields for Servlets within a Web Application
URL Element |
Description |
---|---|
server:port |
The IP address (or host name) and optional port number. To access the default web application for a virtual server, specify only this URL section. You do not need to specify the context_root or servlet_name unless you also wish to specify name-value parameters. |
context_root |
The context path without the leading “/” at which the web application is installed. |
servlet |
Only needed if no servlet-mapping is defined in the web.xml file. |
servlet_name |
The servlet-name (or servlet-mapping if defined) as configured in the web.xml file. |
?name=value... |
Optional servlet name-value parameters. |
In this example, leMort is the host name, MortPages is the context root, and calcMortgage is the servlet name:
http://www.leMort.com/MortPages/servlet/calcMortgage?rate=8.0&per=360&bal=180000
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); |