简体   繁体   中英

Why print statements don't work for forward method of request dispatcher?

I want to understand why don't print statements work when I use forward method.I know in forward method we are redirecting to another servlet but should'nt my print statements before the redirection get printed/shown in the browser.These statements also don't work when I use sendredirect() method but work when I use include() method

public class RdServlet extends HttpServlet
{

public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType("text/html");

PrintWriter out = res.getWriter();
out.println("<html><body>");

 String name=req.getParameter("name");
 String pass=req.getParameter("pass");
 try
 {
 Class.forName("oracle.jdbc.driver.OracleDriver");

 Connection c = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","mca6");
 Statement s = c.createStatement();
 String  s1="select * from emp101  where   name='"+name+"'  and   pass='"+pass+"'";
 ResultSet rs=s.executeQuery(s1);
 out.println("before dispatcher");
 out.println("<br>");
 if(rs.next())
 {

 RequestDispatcher rd=req.getRequestDispatcher("/wel");
 //rd.include(req,res);
 rd.forward(req,res);
 }
else
 {
  RequestDispatcher rd=req.getRequestDispatcher("/err");
  //rd.include(req,res);
  rd.forward(req,res);
 }
 }catch(Exception e){out.println(e);}     
out.println("<br>");
out.println("after  requestDispatcher");
out.println("</body></html>");
}
}

RequestDispatcher.forward() means the complete control for request processing is forwarded to another servlet. The forwarding servlet should not do anything like writing response or committing response. If the response got committed in the calling servlet before the forward, then an IllegalStateException is thrown. IF the response is not yet committed, then the response will be cleared.

If you want to include response from two servlet, use RequestDispatcher.include .

References:

How redirect request from jsp to a servlet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM