File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes Servlet Query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "Servlet Query" Watch "Servlet Query" New topic

Servlet Query

Amit Tayal
Ranch Hand

Joined: Apr 25, 2006
Posts: 51
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

Joined: Feb 05, 2003
Posts: 4727

You make it hard to believe that you tested it when we see request.getWriter() in the code.

A good workman is known by his tools.
Amit Tayal
Ranch Hand

Joined: Apr 25, 2006
Posts: 51
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 Tayal
Ranch Hand

Joined: Apr 25, 2006
Posts: 51
Hi to All
Someone please help me out of this question

Tazim Khan

Joined: Jan 07, 2006
Posts: 4
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...

Rajat Gupta

Joined: Sep 16, 2005
Posts: 7
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.

I agree. Here's the link:
subject: Servlet Query
It's not a secret anymore!