Friday, 21 March 2014

RequestDispatcher Interface in Servlet

Advertisement

RequestDispatcher is an interface which has two important abstract methods defined.
1. include()
2.  forward()
Both the methods are used to delegates the control
from one Servlet to another Servlet / JSP or
from one JSP to another JSP/Servlet .

How to create object of RequestDispatcher ?
This can be achieved in two ways:-

1. With HttpServletRequest object : It can be created by calling getRequestDispatcher(String resourceName) method  by HttpServletRequest object.

public void service(HttpServletRequest req,HttpServletReponse res){

......
RequestDispatcher rd= req.getRequestDispatcher("xxx.jsp");

}

To know more about this click here..!!

2. With ServletContext object : It can be created by calling getRequestDispatcher(String resourceName) method by ServletContext object.

public void service(HttpServletRequest req,HttpServletReponse res){

......
ServletContext ctx= this.getServletContext();
RequestDispatcher rd= ctx.getRequestDispatcher("xxx.jsp");

}

To know more about this click here..!!

The above two ways will create the object of RequestDispatcher. To dispatch the control we need to call either include(req,res) or forward(req,res) with RequestDispatcher object. 

Note : To know the difference between getting RequestDsipatcher object with HttpServleRequest and ServletContext , Click Here..!!

Signature of forward(req,res) 

public void forward(ServletRequest req,ServletReponse res)
throws ServletException, IOException {

}

Forward() method has two parameter of ServletResquest and ServletResponse but we are storing HttpServletRequest and HttpServletResponse object as a parameter. 

It is possible because internally HttpServletRequest extends ServletRequest which means we can able to wrap HttpServletRequest object to ServletRqeuest reference.  This is same with HttpServletResponse and ServletResponse.

public abstract interface HttpServletRequest extends ServletRequest {  

}

Signature of include(req,res)

public void include(ServletRequest req,ServletReponse res)
throws ServletException, IOException {

}

Include() has same signature as forward() method has. Difference is with the operation.

Note : To know the difference between using include() and forward(),  Click Here..!!


EmoticonEmoticon