Intra-Servlet Communication

Sometimes you may need that a Servlet hands off its job to another Servlet or JSP. Intra Servlet communication can be done by means of a Dispatcher or by Redirecting the initial request.

  • Dispatching is done by means of Dispatcher object which allows to complete the request without actually redirecting to user to another site, hence leaving the initial URL unchanged.
  • Redirection moves the initial request to another Servlet or JSP therefore changing the initial request.

Communication between Servlets using a Dispatcher

The following example shows how a Servlet can dispatch its work to another Servlet:

@WebServlet(name = "DispatchServlet", urlPatterns = {"/dispatch"})
public class DispatchServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
     
        ServletContext sc = getServletConfig().getServletContext();
        RequestDispatcher rd = null;
        
        // Do work here
        
        sc.getRequestDispatcher("/AnotherServlet");
        rd.forward(request, response);
    }
 
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        doGet(request, response);
    }
}

As you can see, the capabilities of dispatching are built into the ServletContext, by calling the getRequestDispatcher method passing a String containing the name of the Servlet/JSP that you want to hand off the request to. After a RequestDispatcher object has been obtained, invoke its forward method by passing the ServletRequest and ServletResponse objects to it.

Redirection between Servlets/JSP

In the following example we can see how to redirect the request to another Servlet:

@WebServlet(name = "DispatchServlet", urlPatterns = {"/redirect"})
public class RedirectServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        // Do work here
        response.sendRedirect(redirectUrl);
    }
 
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        doGet(request, response);
    }
}

Found the article helpful? if so please follow us on Socials