How to write a servlet chain

    Servlet Chain:
    Servlet chain is a mechanism provided by java where a servlet can call another servlet.
    Say i have request that is handled by multiple servlets. So the first servlet takes the request process it and send it the second servlet. The output of the previous servlet is input of the next/current servlet.
    By this way the last servlet send the response to the user.

    The main functions for servlet chain are..

    Ads code goes here

    • getRequestDispatcher(Servlet name)—This basically invokes the next servlet

    RequestDispatcher rd = req.getRequestDispatcher(“Servlet2”);

    • include()-if the result of the calling servlet needs to be given to the second called servlet

    RequestDispatcher rd = req.getRequestDispatcher(“Servlet2”);
    rd.include(req, resp);

    • Forard()—- if calling servlet needs to invoke second called servlet

    RequestDispatcher rd = req.getRequestDispatcher(“Servlet2”);
    rd.forward(req, resp);

    • setAttribute—- if the the calling servlet needs to send some data to the second called servlet

    RequestDispatcher rd = req.getRequestDispatcher(“Servlet3”);
    req.setAttribute(“key1”, value1);
    req.setAttribute(“key2”, value2);

    The code will look like

    here the HTML is calling servlet-4
    <html>
        <head>
            <meta http-equiv=”Content-Type” content=”text/html; charset=windows-1252″></meta>
        </head>
        <body>
            <form action=”/Application1-Project1-context-root/servlet4″ method=”get” enctype=”text/plain” name=”sample”>
                <input type=”text” name=”text1″ value=”text” maxlength=”20″ size=”20″/>
                <br/>
                <input type=”text” name=”text2″ value=”text” maxlength=”20″ size=”20″/>
                <br/>
                <input type=”text” name=”text3″ value=”text” maxlength=”20″ size=”20″/>
                <br/>
                <input type=”text” name=”text4″ value=”text” maxlength=”20″ size=”20″/>
                <br/>
                <input type=”submit” name=”Submit” value=”Submit”/>
            </form>
         
        </body>
    </html>

    READ  Learn Servlets in an Easy and Fast way

    The servlet -4 will forward /include the request to servlet-5

    import java.io.IOException;
    import java.io.PrintWriter;

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

    public class Servlet4 extends HttpServlet {
        private static final String CONTENT_TYPE = “text/html; charset=windows-1252”;

        public void init(ServletConfig config) throws ServletException {
            super.init(config);
        }

        public void doGet(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException,
                                                               IOException {
         
            response.setContentType(CONTENT_TYPE);
            PrintWriter out = response.getWriter();
            out.println(“<html>”);
            out.println(“<head><title>Servlet4</title></head>”);
            out.println(“<body>”);
         
            String text1=request.getParameter(“text1”);
            String msg =”<p>The servlet has received a GET. Servle4.This is the reply.</p>”;
            RequestDispatcher rd = request.getRequestDispatcher(“/servlet5”);
            request.setAttribute(“text1”,text1);
         
            if (rd != null)
               rd.include(request, response);
                               or 
               rd.forward(request, response);
            out.println(msg);
            out.println(“</body></html>”);
            out.close();
        }

        public void doPost(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException,
                                                                IOException {
            response.setContentType(CONTENT_TYPE);
            PrintWriter out = response.getWriter();
            out.println(“<html>”);
            out.println(“<head><title>Servlet4</title></head>”);
            out.println(“<body>”);
            out.println(“<p>The servlet has received a POST. This is the reply.</p>”);
            out.println(“</body></html>”);
            out.close();
        }
    }

    New servlet 5 will look like-

    package project1;

    READ  How our custom servlet abide by Servlet Framework??

    import java.io.IOException;
    import java.io.PrintWriter;

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

    public class Servlet5 extends HttpServlet {
        private static final String CONTENT_TYPE = “text/html; charset=windows-1252”;

        public void init(ServletConfig config) throws ServletException {
            super.init(config);
        }

        public void doGet(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException,
                                                               IOException {
            response.setContentType(CONTENT_TYPE);
            PrintWriter out = response.getWriter();
           
            out.println(“<html>”);
            out.println(“<head><title>Servlet5</title></head>”);
            out.println(“<body>”);
           //getting the text value send from first HTML via servlet-4
            String text1 = (String)request.getAttribute(“text1”);
            out.println(“<p>The servlet has received a GET. Servlet5. This is the reply.</p>”+text1);
         
            out.println(“</body></html>”);
            out.close();
           
             
        }

        public void doPost(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException,
                                                                IOException {
            response.setContentType(CONTENT_TYPE);
            PrintWriter out = response.getWriter();
            out.println(“<html>”);
            out.println(“<head><title>Servlet5</title></head>”);
            out.println(“<body>”);
            out.println(“<p>The servlet has received a POST. This is the reply.</p>”);
            out.println(“</body></html>”);
            out.close();
        }
    }

    READ  What Is Single Directory Architecture For JSP or Serlet

    Share and Enjoy !

    1 thought on “How to write a servlet chain”

    1. Hello, This is exactly what I was looking for. I'm trying to make 3 servlets for user authentication, database registry and a success message but now I'm wondering if it's worth it making 3 servlets instead of 1, since at the end it's the same thing (the code runs exactly the same) and even a bit more because of the "chaining"? The ideal for me would be to let the authentication servlet let auth many requests at a single time (the same with the DB registry and the success message) but it would be too complicated for me right now.

    Leave a Comment

    Your email address will not be published. Required fields are marked *