by Dinesh Thakur Category: Servlet Chaining

This method of RequestDispatcher interface includes the content of web resource (servlets, JSP and HTML file) in the response. In other words, this method allows server-side to include the response of destination program to source program. Here ServletResponse object are passed as the argument of include () method.

The ServletResponse object has its path elements, and parameters remain unchanged from the caller’s. The included servlet cannot change the response status code or set headers; any attempt to make change is ignored.

The request and response parameters must be either the same objects as were passed to the calling servlet’s service method or be subclasses of the ServletRequestWrapper or ServletresponseWrapper classes that wrap them.

Parameters

request: a ServletRequest object that contains the client's request

response: a ServletResponse object that contains the servlet's response

Throws

ServletException - if the included resource throws this exception

IOException - if the included resource throws this exception                       

                     RequestDispatcher include method

Here in Srvl program (srcprog), the HTML output will not be discarded. Moreover, Srvl and Srv2 servlet programs HTML outputs together go to browser window as response.

The rd.include (-,-) method performs include response mode if servlet chaining is performed. Both Srvl and Srv2 programs will use the same request and response object so the request data coming to Srvl is visible and accessible in Srv2. To pass additional data between Srvl and Srv2 use request attributes.

The browser window gets response from Srvl program by having the HTML output of Srvl and Srv2 programs. Srv2 and the HTML output can be there in the HTML output of Srv2 by calling rd.include (-,-) method in the required place. Srvl and Srv2 can be present in the same web applications of the same server. The Srv2 can be a servlet program or HTML program. In the real time rd.include (-,-) is useful in including the output of (HTML output) main web resource programs.

Problem:

                      How to use RequestDispatcher include method

All web pages of a website generally contain the same header and footer contents but the main content will be changed in every web page. In the above diagram header and footer logics are not reusable, because they are placed in all the three servlet programs even though they are the same for all the three servlet programs.

Solution:

                     How to use RequestDispatcher include method

In the solution diagram header and footer logics are separated from the main

servlet programs of web application, and they are placed in two separate web

resource programs but their HTML output is included (using rd.include (-,))) in the main programs HTML output. This indicates header and footer logics are made as reusable logics.

Sample code based on solution diagram:

 

HeaderSrv.java (having header logic)

public class Headersrv extends HttpServlet

{

     public void service (_,_) throws ServletException, IOException

    {

             --------------PrintWriter pw=res.getWriter ();

             -------------- res.setContentType (“text/html”);

             pw.println (“<font color=red size=6> D I N E S H </font>”);

             pw.println (“<br><br><br>”); //don’t place pw.close in HeaderSrv

    }

}//headurl is the HeaderSrv servlet program

Footer.html (Having Footer Logic)

<hr>

<br><br><br>

<b><i>&copy; All rights reserved </b></i>

Main servlet programs

public class Headersrv extends HttpServlet

{

      public void service (_,_) throws ServletException, IOException

     {

          try

         {

              RequestDispatcher rdl=null, rd2=null

              rdl=req. getRequestDispatcher (“/headerurl”);

              rdl.include (req, res);

              ----------

              -----------//logic to generate main content of web page              

              -----------          

            //include footer content from Footer.html

            rd2=req.getRequestDispatcher (“/footerurl”);

            rd2.include (req, res);

         }

          catch (Exception e)

         {

              e.printStackTrace ();

         }

     }

}

Once the rd.forward (-,-) method is executed in the source servlet program, the effect of rd.include (-,-) method call will not be there in that servlet program, which means the rd.forward (-,-) method call discards both the directed and included HTML output of source servlet program. For example, application on both rd.forward (-,-), rd.inciude (,) method calls refer app (6).For example, application on rd.forward (-,-), rd.inciude (-,-) method calls refer app (8). While working with rd.forward (-,-) method.

Do not commit the response in source servlet program by calling pw.close ()

method before rd.forward () method call because this process throws java.lang.IllegalException () (can't forward after response has been committed).

Note: pw.close () commits the response of web resource program, that is, it does not allow of addition further content to the response.

Example application

Step 1: Prepare the deployment directory structure of web application.

                           deployment directory structure of web application

 

Step 2: Develop the source code of the above servlet program or web Application.

home.html

<body bgcolor=’red’>

          <center>

                 <form action= “DBurl” method= “GET”>

                       EMP_ID : <input type= “text” name= “t1”>

                                <input type= “submit” value= “search”>

                 </form>

          </center>

</body>

Footer.html

<hr><br><br><hr>

<center>

      <font color= ‘blue’ size= ‘7’>

          <marquee> welcome to java </marquee>

      </font>

</center>

web.xml

<web-app>

   <servlet>

       <servlet-name>abc </servlet-name>

       <servlet-class> DBSrv </servlet-class>

   </servlet>

   <servlet-mapping>

      <servlet-name> abc </servlet-name>

      <url-pattern> /DBurl </url-pattern>

   </servlet-mapping>

   <welcome-file-list>

       <welcome-file> home.html </welcome-file>

   </welcome-file-list>

   <servlet>

       <servlet-name> h </servlet-name>

       <servlet-class> header </servlet-class>

   </servlet>

   <servlet-mapping>

       <servlet-name> h </servlet-name>

       <url-pattern> /header </url-pattern>

   </servlet-mapping>

</web-app>

DBSrv

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import java.sql.*;

publicclass DBSrv extends HttpServlet

{

     Connection cn;

     Statement st;

     RequestDispatcher rd;

     publicvoid init (ServletConfig cg)

     {

          try

          {

               Class.forName ("oracle.jdbc.driver.OracleDriver");

               cn=DriverManager.getConnection

              ("jdbc:oracle:thin:@localhost:1521:XE", "system", "manager");

              System.out.println ("connected database");

              st=cn.createStatement ();

          }

          catch (Exception e)

          {

               System.out.println ("caught");

          }

     }

      publicvoid doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException

     {

          res.setContentType ("text/html");

          PrintWriter pw=res.getWriter ();

          try

         {

              rd=req.getRequestDispatcher ("/header");

              rd.include (req, res);

              String empno=req.getParameter ("t1");

              Result rs = st.executeQuery ("select * from EMP where EMPNO="+empno);

              System.out.println ("retrieve emp information");

              if (rs.next ())

              {

                   pw.println ("<center><table border='9' color='red'> <tr> <th>ENAME </th> <th> EMPNO </th> <th> SAL </th>

<th>EADD </th> <th> MAILID </th> <th> PHNO </th> </tr>");

                   pw.println ("<tr> <td>"+rs.getString(1) +"</td>");

                   pw.println ("<td>"+rs.getString (2) +"</td>");

                   pw.println ("<td>"+rs.getString (3) +"</td>");

                   pw.println ("<td>"+rs.getString (4) +"</td>");

                   pw.println ("<td>"+rs.getString (5) +"</td>");

                   pw.println ("<td>"+rs.getString (6) +"</td>");

                   pw.println ("</tr> </table>");

              }

              rd=req.getRequestDispatcher ("Footer.html");

              rd.include (req, res);

         }

         catch (Exception ee)

         {

              pw.println ("please enter valid emp id");

         }

    }

}

Header.java

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import java.sql.*;

publicclass Header extends HttpServlet

{

     publicvoid doGet (HttpServletRequest req, HttpServletResponse res)

     throws ServletException, IOException

     {

          PrintWriter pw=res.getWriter ();

          pw.println (“<font color='red' size='7'><br><br><br><b>”);

          pw.println (“<marquee behavior=’alternate’> welcome to interface software </marquee>”);

          pw.println (“</font><hr>”);

     }

}

Step 3: Compile the source files of allservlet programs.

Step 4: Configure all the four servlet programs in web.xm1 file having four different URL patterns.

Step 5: Start the server (Tomcat).

Step 6: Deploy the web application.

Copy Srvchain folder to Tomcat_home\ webapps folder.

Step 7: Create table Emp in Oracle database server

Syntax: Create table emp (empno number (6), ename varchar2 (25), sal

number (6), Eadd varchar2 (25), mail_id varchar2 (25);

Step 8: Insert the value in emp table

Syntax: insert into emp values (101, ‘Dinesh’, ‘10000’, ‘bbsr’, ‘bbsr’,

This email address is being protected from spambots. You need JavaScript enabled to view it. ’, ‘98564’);

Step 9: Test the web application.

Open browser window type this url: http://localhost:2020/Srvchain/ home.html





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.