how to include one servlet into another Servlet Essentials Servlet Include

Include Servlets

Here we will talk about how to include one servlet into another.Including a servlet is as same as include that servlet`s code into the servlet in which it is included. This concept is used in places where we need to have reusable servlet codes which can be used at multiple places.Suppose we have some common code like login or some other logic which can be used at various places.So,what can be done is write that very code in a servlet and that can be used at various places.The inclusion basically is a dynamic inclusion which means the response of the included servlet is included in the includer servlet.The RequestDispatcher class gives the method for inclusion.The RequestDispacher class as the name suggests is the request delegater. The RequestDispatcher instance can be get from the request object inside the doPost or doGet method.Here the request and response objects are passed as paramters from the servlet code where inclusion code is written.The example code is written below :

import javax.servlet.*;
import javax.servlet.http.*;

public class RequestDispatch extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      ServletContext sc = this.getServletContext();
      RequestDispatcher rDis = sc.getRequestDispatcher("/login");
      if (rDis != null){
          rDis.include(request, response);
      PrintWriter out = response.getWriter();
      out.print("Output after the content of login");

Here we can see that login is included in the RequestDispatch servlet.In the getting if RequestDispatch instance from the request object we need to give the entry in <url-pattern> tag for the servlet.Then we can find that if we are printing anything from the included the servlet it will appear when we run RequestDispatch servlet as the login servlet is included.

Number of View :8152


  1. No comments yet.

Content Protected Using Blog Protector By: PcDrome.