Sobes.tech
Middle

How can one servlet be called from another servlet?

sobes.tech AI

Answer from AI

The mechanisms RequestDispatcher are used to call one servlet from another.

There are two main methods:

  1. forward(): Transfers control to another resource (servlet, JSP, or HTML). The request and response remain the same. The URL in the browser's address bar does not change.

    // Obtain a RequestDispatcher for the "AnotherServlet"
    RequestDispatcher dispatcher = request.getRequestDispatcher("/anotherServlet");
    // Forward the request and response to another servlet
    dispatcher.forward(request, response);
    

    Usage:

    • Ideal for internal request processing, where one servlet prepares data and another displays it.
    • Cannot be used after some data has already been sent in the response (e.g., after response.getWriter().write(...)).
  2. include(): Includes the content of another resource in the current response. Control is temporarily passed to another resource, which processes it, and then control returns to the calling servlet. The URL in the browser's address bar does not change.

    // Obtain a RequestDispatcher for the "AnotherServlet"
    RequestDispatcher dispatcher = request.getRequestDispatcher("/anotherServlet");
    // Include the content of another servlet in the current response
    dispatcher.include(request, response);
    // After include() execution, processing can continue in the current servlet
    // e.g.: response.getWriter().write("Content from calling servlet.");
    

    Usage:

    • Suitable for including common content fragments (e.g., header or footer of a page), generated by other servlets or JSPs.
    • Can be used multiple times.

The URL path specified in getRequestDispatcher() can be relative or absolute with respect to the application context. For example:

  • /anotherServlet: Path relative to the application root.
  • anotherServlet: Path relative to the current servlet (not recommended, as it may be unclear).

Important: You cannot use response.sendRedirect() to "call" another servlet in the same sense as forward() or include(). sendRedirect() sends an HTTP redirect to the client (browser), which then makes a new request to the specified URL. All request attributes are lost, and a new request-response cycle is created.