1

I am trying to use RequestDispatcher's incluce method in my jsp page. The problem is that it is not giving desired output.

Here is my code:

    <%

out.println(" end");
out.println(" starts");
RequestDispatcher rd=request.getRequestDispatcher("myfile.jsp");

rd.include(request,response);

%>

and myfile.jsp :

  <%="good"%>

It is giving output as :

good end starts

but i expect output to be : end starts good.

Can any one please explain. Thanks

Himanshu
  • 33
  • 6

1 Answers1

0

It is because you have include the response from your RequestDispatcher class to the jsp , so it includes the processing done by the calling jsp( (i.e) printing the statements out.println ).

From Java docs,

If the resource is static, the include method enables programmatic server-side includes. If the resource is a web component, the effect of the method is to send the request to the included web component, execute the web component, and then include the result of the execution in the response from the containing servlet.

An included web component has access to the request object but is limited in what it can do with the response object.

It can write to the body of the response and commit a response.

It cannot set headers or call any method, such as setCookie, that affects the headers of the response. It is often useful to include another web resource, such as banner content or copyright information) in the response returned from a web component.

Hope this helps !!

Santhosh
  • 8,181
  • 4
  • 29
  • 56
  • but if i use same statements in servlet,say myserv.java then it generates the expected response. why? – Himanshu May 06 '14 at 11:45
  • see [this](http://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-session-variables-and-multithreading) and [this](http://stackoverflow.com/questions/2095397/what-is-the-difference-between-jsf-servlet-and-jsp/2097732#2097732) to know how servlet and jsp works exactly – Santhosh May 06 '14 at 12:20
  • my question is why it is executing request dispatcher first even it is written afterwards. – Himanshu May 07 '14 at 06:41
  • It is because jsp first executes the **Declarations** followed by the **Expressions** . Considering your `out.println` as the expression – Santhosh May 07 '14 at 06:58