Difference between forward and include of RequestDispatcher

来源:互联网 发布:网络测试仪使用方法 编辑:程序博客网 时间:2024/05/16 05:24

forward is used to forward a request, that is control is transfered tothe new servler/jsp. u shud take care to not put any our.println()statements in the servlet from where u plan to call forward method. infact u cant even fire response.getWriter() method in this case. u canonly do that in the servlet to which the control is bein fwded

include - means that the new servlet/jsp will be procesed and anyout.println()/html stuff will be included and then control will comeback to the servlet/jsp that called include method.

 

 

RequestDispatcher接口所定义的forward()方法可以将HTTP请求转送给其他Web资源(例如Servlet、JSP或HTML)进行处理,并产生HTTP回应。

调用forward()方法时必须注意下列两点:

1.      在HTTP回应被“确认”(committed)以前才能调用forward()方法(这里的“确认”是指将HTTP回应的内容主体送回用户端),否则将拋出IllegalStateException异常。

2.      调用forward()方法后,原先存放在HttpResponse对象中的内容将会自动被清除.


RequestDispatcher接口的include()方法与forward()方法非常类似,惟一的不同在于:利用include()方法将HTTP请求转送给其他Servlet后,被调用的Servlet虽然可以处理这个HTTP请求,但是最后的主导权仍然是在原来的Servlet。换言之,被调用的Servlet如果产生任何HTTP回应,将会并入原来的HttpResponse对象。