This method forwards a request from a servlet to another resource (servlet, JSP file or HTML file) on the server. It enables one servlet to do prelude processing of a request and another resource to create the response.
For a RequestDispatcher obtained via getRequestDispatcher (), the
ServletRequest has its own path elements and parameters adjusted to match the path of the target resource.
forward (-,-) should be called before the response has been committed to the client (before response body output has been flushed). If the response has already been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward.
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 U4 or ServletResponseWrapper classes that wrap them.
Parameters
request – a ServletRequest object that represents the request the client makes of the servlet
response – a ServletResponse object that represents the response the servlet returns to the client
Throws
ServletException – if the target resource throws this exception
IOException – if the target resource throws this exception
IllegalStateException – if the response was already committed
The HTML output of Srv1 will be discarded and only the HTML output of Srv2 will go to browser window as response.
Key Points:
• The rd.forward (-,-) method is there to perform forwarding request mode of servlet chaining.
• Both Srv1 and Srv2 servlet programs will use the same request and response objects so the request data coming to Srv1 (like request parameters, headers, etc.) are visible and accessible in Srv2 program.
• To pass additional data between Srv1 and Srv2, programs use “request” attributes.
• All the statements placed in Srv1 program before and after the rd.forward () method will be executed, but the entire HTML output of Srv1 program will be discarded.
• Both the Srv1 and Srv2 can be there either in the same web application or two different of same server.
• Srv2 can be a servlet program or JSP program or HTML program.
• rd.forward (-,-) is useful to configure Error Servlet for other main Servlet programs of the web application.
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 in displaying exception-related messages as non-technical guiding messages on browser window. Exceptions are raised in other servlet programs of web application.
Sample code to configure error servlet
ErrSrv.java
public class ErrSrv extends HttpServlet/GenericServlet {
public void service(-,-)throws ServletException,IOException {
———res.setContentType(“text/html”);
———PrintWriter pw=res.getWriter();
———pw.println(“<font color=red>Internal Problem</font>”);
pw.println(“<br>Goto<ahref=input.html>Home</a>“);
} //service (-,-)
} //class
// “/eurl” is the url pattern of ErrSrv program (in web.xml)
DBSrv.java (Main servlet program of web application)
public class DBSrv extends HttpServlet {
public void init() {
———-
———-same as previous application
———-
}
public void doGet(-,-)throwsServletException,IOException {
try {
———
———same as previous application
———
}
catch(Exception e) {
try {
RequestDispatcher rd=req.getRequestDispatcher(“/eurl”);
rd.forward(req,res);
}
catch(Exception e1) {
e1.printStackTrace();
}
}
}
public void doPost(-,-)throwsServletException,IOException {
doGet(req,res);
}
public void destroy() {
————
————
}
}
• In the above sample code, when exception is raised in the doGet (-,-) method of DBSrvServlet program, the servlet (ErrSrv) program will be executed automatically because of the rd.forward (-,-) method call.
• If Servlet program contains rd.forward () method call then that Servlet program HTML output will be discarded but their System.out.println (“—”) statements will not be discarded.
• Always keep rd.forward (-,-) method call in source servlet program with condition statement so that source servlet program will be discarded only when that condition is satisfied otherwise the HTML output will not be discarded.
• In projects rd.forward (-,-) is useful in configuring ErrorServlet and in making web applications.
Step 1: Prepare the deployment directory structure of web application.
Example Application
Step 2: Develop the source code of the above servlet program or web application.
home.html
<bodybgcolor=’red’>
<center>
<formaction= “DBurl” method= “GET”>
EMP_ID : <inputtype= “text” name= “t1”>
<inputtype= “submit” value= “search”>
</form>
</center>
</body>
DBSrv.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class DBSrv extends HttpServlet {
Connection cn;
Statement st;
RequestDispatcher rd;
publicvoidinit(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(Exceptione) {
System.out.println(“caught”);
}
}
public void doGet(HttpServletRequestreq,HttpServletResponseres)
throws ServletException,IOException {
res.setContentType(“text/html”);
PrintWriter pw=res.getWriter();
try {
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(Exceptionee) {
RequestDispatcher rd=req.getRequestDispatcher(“/e”);
rd.forward(req,res);
}
}
}
Err.java
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Err extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException, IOException {
PrintWriter pw=res.getWriter();
pw.println(“<center><fontcolor=‘red’size=‘6’><marquee>
INTERNAL PROBLEM</marquee></font></center>”);
pw.println(“<ahref=‘http://localhost:2020/DBApp/home.html’>TRYAGAIN</a>”);
}
}
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> e </servlet-name>
<servlet-class>Err </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> e </servlet-name>
<url-pattern> /e </url-pattern>
</servlet-mapping>
</web-app>
Step 3: Compile the source files of all servlet programs.
Step 4: Configure all the four servlet programs in web.xml file having four different URL patterns.
Step 5: Start the server (Tomcat).
Step 6: Deploy the web application and Copy DBApp 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’,‘[email protected]’, ‘98564’);
Step 9: Test the web application.
Open browser window type these urls: https://ecomputernotes.com:2020/DBApp/ home.html
If the enter user wrong emp-id, Exception occurs, and Err Servlet program output comes.
The limitation of RequestDispatcher object based servlet chaining is that it cannot be used when the source servlet program and destination web resource program are placed in two different web applications of the same server (very few servers are supporting this) or in two different web applications of two different servers. To overcome this problem, use send redirection concept of response.sendRedirect (-) method.