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..

  • 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>


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;

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();
    }
}

About the author :
author

This post was written by: Animesh Chatterjee. Animesh is a professional blogger, web designer and frontend web developer. Animesh is an enthustic and have passion to share his idea and creativity with this blog and provide tricks, tips and information for visitors. Thanks for visiting. You can follow Animesh in the following channel

You may also like :

{ 1 comments... read them below or add one }

Anonymous said...

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.

Post a Comment