In Java servlets, if you want to call another servlet from within your current servlet, you have a few options depending on what exactly you mean by “call”:
1. Forward the request (internal call, no redirect visible to the client)
You can forward the current request to another servlet inside the same server using a RequestDispatcher.
RequestDispatcher dispatcher = request.getRequestDispatcher("/otherServlet");
dispatcher.forward(request, response);
The control is passed to otherServlet.
URL in browser stays the same (client doesn’t know).
Request and response objects are shared.
2. Include output from another servlet (embed response)
You can include another servlet’s output into your current response:
RequestDispatcher dispatcher = request.getRequestDispatcher("/otherServlet");
dispatcher.include(request, response);
The output of otherServlet is embedded in the response.
Useful if you want to combine responses (e.g., page fragments).
3. Send Redirect (external, client-visible redirect)
You can redirect the client to another servlet:
response.sendRedirect(request.getContextPath() + "/otherServlet");
Browser will make a new request to /otherServlet.
URL in browser changes.
Request and response are not shared anymore (new request).
Summary Table:
| Way | Method | Control | Browser URL Changes? | Request/Response Shared? |
|---|---|---|---|---|
| Forward | RequestDispatcher.forward() | Server-side | No | Yes |
| Include | RequestDispatcher.include() | Server-side | No | Yes |
| Redirect | response.sendRedirect() | Client-side | Yes | No |
Example:
Suppose you are in FirstServlet and want to call SecondServlet internally.
public class FirstServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Some logic
System.out.println("Before calling SecondServlet");
RequestDispatcher dispatcher = request.getRequestDispatcher("/SecondServlet");
dispatcher.forward(request, response);
// Code here won't execute after forward!
System.out.println("After calling SecondServlet"); // Will not run
}
}