Servlet Chaining in Java

Servlet Chaining in Java

In this article, I am going to discuss Servlet Chaining in Java-based Web Application. Please read our previous article where we discussed the basics of RequestDispatcher in Servlet. At the end of this article, you will understand the following pointers in detail.

  1. What is Servlet Chaining?
  2. What is Request Dispatching in the context of a java web application?
  3. Develop a java a WEB application in which inter servlet-communication is implemented using the forward mechanism of request dispatching.
  4. Example using Include Mechanism of Request Dispatcher
  5. What are the Different Approaches to Create a RequestDispatcher object in Java?
  6. What is the difference between getRequestDispatcher() and getNamedDispatcher() methods?
  7. What is the difference between the RequestDispatcher object that is created based on the request object and the servletContext object?
  8. What is Error Servlet?
What is Servlet Chaining?

Taking the request from a browser window and processing that request by using multiple servlets as a chain is called servlet chaining. In servlet chaining, we perform communication between servlet programs to process the request given by a client.

What is Servlet Chaining?

All servlet programs that participate in a servlet chaining will use the same request and response objects because they process the same request that is given by the client.

To perform servlet chaining we need the RequestDispatcher object. RequestDispatcher object means it is the object of a container supplied java class implementing javax.servlet.RequestDispatcher interface.

What is Request Dispatching in the context of a java web application?

One servlet delegating the request processing duty to another servlet is nothing not but request dispatching. Inter-servlet communication is implemented using request dispatching i.e. one servlet can communicate with another servlet of the same application using request dispatching.

Two steps are involved in the implementation of request dispatching.

Step1. Create RequestDispatcher object
          rd = request.getRequestDispatcher(“other servlet public URL name”);

Step2. Delegate the request to the other servlet
         rd.forward(request, response);
         Or
         rd.include(request, response);

In the case of the forward mechanism of request dispatching the second servlet is responsible for the response generation. In the case of the include mechanism, only the first servlet is responsible for the response generation.

Note: When the client request is complex or to share the duty of client request between multiple servlets, request dispatching is implemented.

Develop a java a WEB application in which inter servlet-communication is implemented using the forward mechanism of request dispatching.

What is Request Dispatching in the context of a java web application?

The user submits the form after entering the input, GrossServlet receiving the client request and capturing the user input. The GrossServlet calculate the Gross salary and then the GrossServlet switching the control to NetServlet using the forward mechanism of request dispatching. NetServlet Calculating deduction based on the Gross salary and finally calculating net salary (take home salary).

Develop a java a WEB application in which inter servlet-communication is implemented using the forward mechanism of request dispatching.

web.xml
<web-app >
    <servlet>
       	 <servlet-name>NetServlet</servlet-name>
        	<servlet-class>NetServlet</servlet-class>
    </servlet>
    <servlet-mapping>
       	 <servlet-name>NetServlet</servlet-name>
       	 <url-pattern>/target</url-pattern>
    </servlet-mapping>
        <servlet>
        	<servlet-name>GrossServlet</servlet-name>
        	<servlet-class>GrossServlet</servlet-class>
    </servlet>
    <servlet-mapping>
       	 <servlet-name>GrossServlet</servlet-name>
        	<url-pattern>/source</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        	<welcome-file>basic.html</welcome-file>
    </welcome-file-list>
</web-app>
Basic.html
<html>
 <body bgcolor =" cyan">
    <center>
        <h1>SALARY DETAILS</h1>
        <form action="./source">
            BASIC: <input type="text" name="basic">
            <br><br>
            <input type="submit" value="submit">
        </form>
    </center>
    </body>
</html>
GrossServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class grossServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
           float basic = Float.parseFloat(request.getParameter("basic"));
           float da = basic * 0.8f;
           float hra = basic * 0.3f;
           float gross = basic + da + hra;
           request.setAttribute("gr", gross);
           RequestDispatcher rd = request.getRequestDispatcher("/target");
           rd.forward(request, response);        
    }
}
NetServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class NetServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException 
{
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        //String grs = (String)request.getAttribute("gr");
        //float gross = Float.parseFloat(grs);
        float gross = (Float) request.getAttribute("gr");
        float deduction = gross * 0.05f;
        float net = gross - deduction;
        out.println("<html>");
        out.println("<body>");
        out.println("net salary is" + net);
        out.println("</body>");
        out.println("</html>");
    }
}
Same Example using Include Mechanism of Request Dispatcher.

Example using Include Mechanism of Request Dispatcher

The user submits the form after entering the input, GrossServlet receiving the client request and capturing the user input. GrossServlet calculating the Gross salary and then the GrossServlet switching the control to NetServlet using forward mechanism of request dispatching. NetServlet Calculating deduction based on the Gross salary and finally calculating net salary (take-home salary).

Note: basic.html and web.xml are from the previous application

GrossServlet.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class grossServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
           float basic = Float.parseFloat(request.getParameter("basic"));
           float da = basic * 0.8f;
           float hra = basic * 0.3f;
           float gross = basic + da + hra;
           request.setAttribute("gr", gross);
           RequestDispatcher rd = request.getRequestDispatcher("/target");
           rd.include(request, response);   
        float net = (Float) request.getAttribute("nt");
        out.println("<html>");
        out.println("<body>");
        out.println("net salary is" + net);
        out.println("</body>");
        out.println("</html>");
    }
}
NetServlet.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class NetServlet extends HttpServlet 
{
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        float gross = (Float) request.getAttribute("gr");
        float deduction = gross * 0.05f;
        float net = gross - deduction;
        request.setAttribute("nt", net);
    }
}
What are the Different Approaches to Create a RequestDispatcher object in Java?

Approach1: (By using request object)
Example: In Servlet1 source code
               RequestDispatcher rs = request.getRequestDispatcher(“/public URL of Other servlet”);
               rd.forward(request, response);
               or
               rd.include(request, response);

Approach2: (By using ServletContext object)
Example: In Servlet1 source code
               ServletContext sc = getServletContext();
               RequestDispatcher rs = sc.getRequestDispatcher(“/public URL of Other servlet”);
               rd.forward(request, response);
              or
              rd.include(request, response);

Approach3: (By using ServletContext object)
Example: In Servlet1 source code
               ServletContext sc = getServletContext();
               RequestDispatcher rs = sc.getNamedDispatcher(“logical name of destination servlet”);
               rd.forward(request, response);
               or
               rd.include(request, response);

What is the difference between getRequestDispatcher() and getNamedDispatcher() methods?

getRequestDispatcher():

  1. Invokable on both ServletContext and request object.
  2. Express URL pattern of destination servlet program or file names or destination JSP or HTML program as the argument value.
  3. This method generated RequestDispatcher object can point to the destination servlet, JSP program, and HTML program.

getNamedDispatcher():

  1. Invokable only on ServletContext object.
  2. Express the logical name of the destination servlet or JSP program as the argument value.
  3. This method generated RequestDispatcher object can point only the destination Servlet and JSP program.
What is the difference between the RequestDispatcher object that is created based on the request object and the servletContext object?

The request object based RequestDispatcher object expects that the source servlet program and destination web resource program must be in the same web application. The ServletContext object-based RequestDispatcher object allows to keep the source servlet program and destination web resource program either in the same web application or in two different web applications of the same server but they cannot be there in two different web application of two different servers.

What is the difference between the RequestDispatcher object that is created based on the request object and the servletContext object?

Here Servlet1 can use both request object and ServletContext object-based RequestDispatcher object.

Servlet chaining in Java Application

Here servlet1 should use ServletContext object based RequestDispatcher object.

Servlet chaining in Java Application

This kind of servlet chaining is not possible with the RequestDispatcher object, we need to use the Send Redirection concept. So, servlet chaining is all about performing servlet-servlet communication or we can say inter-servlet communication.

When the client request is complex or to share the duty of client request processing between servlets, request dispatching is implemented.

What is Error Servlet?

The servlet program that executes only when exceptions are raised in other servlet program is called Error Servlet. This Servlet is useful to display exception related messages as non-technical guiding messages on browser window when exceptions are raised in other servlet programs of the web application.

In the next article, I am going to discuss SendRedirect in servlet. Here, in this article, I try to explain Servlet chaining in Java Application. I hope you enjoy this Servlet chaining in Java Application article.

Leave a Reply

Your email address will not be published.