File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Servlet Query

 
Amit Tayal
Ranch Hand
Posts: 51
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All
Please help me in solving the below mentioned Question:

Q: Consider the following code snippets. What will be displayed on the browser when a GET request is sent to FirstServlet assuming that the buffer is large enough to hold all the data before sending the data to the client?
Code Snippet:

Option 1: Only Page2
Option 2: IllegalStateException at Runtime

Ans: 2

As per my understanding Option 1 should be correct as I have tested this case.

Code Snippet
===================
In the doGet() of FirstServlet:
PrintWriter out = response.getWriter();
out.println("<html><body>Page 1");
RequestDispatcher rd = request.getRequestDispatcher("NextServlet");
rd.forward(request, response);
out.println("<br>Page 3</body></html>");
In the doGet() of SecondServlet:
PrintWriter out = request.getWriter();
out.println("<br>Page 2");

 
Marc Peabody
pie sneak
Sheriff
Posts: 4727
Mac Ruby VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You make it hard to believe that you tested it when we see request.getWriter() in the code.
 
Amit Tayal
Ranch Hand
Posts: 51
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I did not test the same code but tested the code similar to it.
Please read request.getWriter() as response.getWriter()

Now what will be the answer for the question??

Amit
 
Amit Tayal
Ranch Hand
Posts: 51
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi to All
Someone please help me out of this question

Amit
 
Tazim Khan
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think once you forward to a page with rd.forward(..) you shouldn't attempt to print like "out.println()" right after forwarding to a different page. It may generate exception...

Tazim
 
Rajat Gupta
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The output of "Page 2" is correct.

After any Requestdispatch or sendRedirect or jsp:forward, all the contents of the forwarding page are lost. That's what is happening for the Page1. Also, after the RequestRedirect, the control from page1 is transferred to the called jsp, so "page3" never gets printed.
The reason why the IllegalStateexception won't occur, is that, the response is never "committed" or "sent to the browser". Hope it helps.

Rajat
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic