RequestDispatcher include method

FRAMEWORK/SERVLET 2014. 11. 5. 17:57

RequestDispatcher include

Hello, continuing the previous article, we will learn about RequestDispatcherincludemethod.

Why is it needed?

The forward method redirects to another resource which is called through a resource. The response of calling resource is not sent to the client. It is lost. What should be done if we want to retain the response of calling resource and called resource? What if we want to show them both to the client?

How to do it?

RequestDispatcher include method comes to the rescue. This is what javadoc says about RequestDispatcher include .

Includes the content of a resource (servlet, JSP page, HTML file) in the response. In essence, this method enables programmatic server-side includes.

Let us see a practical example of  RequestDispatcher include  method.

Step 1: Create dynamic web project.

Create a new dynamic web project called ServletJSPExamples using eclipse IDE.

Step 2: Create and configure DispatcherServlet.

Create a new servlet called DispatcherServlet which will useRequestDispatcher includemethod to call another resource.

Configure it in web.xml

 Step 3: Create Hello.jsp

 Step 4: Run application.

Deploy the application under tomcat. Start it and hit the urlhttp://localhost:8080/ServletsJSPExamples/DispatcherServlet .

You will see the output as :

 

 Explanation:

  • PrintWriter is created in DispatcherServlet so that response can be written.
  • After  out.println();   statement, a RequestDispatcher is created for Hello.jsp   using RequestDispatcher rd =request.getRequestDispatcher("Hello.jsp");
  • rd.include(request, response);  i.e.  RequestDispatcher include  method sends HttpServletRequest and HttpServletResponse objects to the resource for which RequestDispatcher is created. So in this case, it’s Hello.jsp .
  • Control is forwarded to Hello.jsp   and the contents are written to response.
  • Now as we have used  RequestDispatcher include  method, the response fromDispatcherServlet is combined with the response of Hello.jsp . It acts as a dynamic include.
  • So both responses are printed onto the web page.

The diagram below will elaborate it clearly.




출처 - http://www.thejavageek.com/2013/12/11/requestdispatcher-include-method/

'FRAMEWORK > SERVLET' 카테고리의 다른 글

RequestDispatcher forward method  (0) 2014.11.05
서블릿이란  (0) 2014.11.05
jsp 와 servlet 의 차이  (0) 2014.11.05
서블릿  (0) 2014.11.05
: