The following example code shows a program to Demonstrate the Use of include() Method in Servlets.

Here is an example of a dynamic web application using servlets to demonstrate the include() method.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class IncludeServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Include Servlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Include Servlet</h1>");
    out.println("<p>This is the content of the Include Servlet.</p>");
    RequestDispatcher dispatcher = request.getRequestDispatcher("/IncludedServlet");
    dispatcher.include(request, response);
    out.println("<p>This is the end of the Include Servlet.</p>");
    out.println("</body>");
    out.println("</html>");
  }
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class IncludedServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<p>This is the content of the Included Servlet.</p>");
  }
}

In this example, the IncludeServlet class handles GET requests and generates an HTML response. The response includes the content of the IncludedServlet by using the include() method. The include() method allows one servlet to include the response from another servlet as part of its own response. The include() method is useful for cases where multiple servlets need to contribute content to a single response, or where a common header or footer needs to be included in the responses from multiple servlets. When the include() method is called, the included servlet is executed and its response is included in the response from the calling servlet. In this example, the response from the IncludedServlet is included in the response from the IncludeServlet.


Further Reading

Understanding Enterprise Java Beans

Java Practice Exercise

programmingempire

Princites