JBridge

JBridge: Certification Question Of The Day

JBridge Home >> Certification Questions >> Question for Thursday May 15th Thursday May 15th

Identify true statements about the following servlet code? (the line numbers are not part of the code) (1 correct answer)

11  RequestDispatcher rd = request.getRequestDispatcher("/InventoryServlet");
12  PrintWriter out = response.getWriter();
13  out.write("Inventory Report");
14  out.flush();
15  out.close();
16  rd.include(request, response);



A The servlet will not run, as it will not compile.
B The output from "InventoryServlet" is returned to the requester.
C The output from "InventoryServlet" is returned to the requester, prefaced by the words "Inventory Report".
D A runtime error occurs at line 16, giving rise to an IllegalStateException.
E Line 16 does not execute.
F In line 11, the "/" in "/InventoryServlet" is incorrect. Only a RequestDispatcher returned from ServletContext can have a getRequestDispatcher parameter beginning with a "/".
G Only the words "Inventory Report" are returned to the requester.
Page down for the answer...











































The Answer

G is the correct answer.
Because the response output stream has been closed, the "include" at line 16 has no effect. So the output from "InventoryServlet" is not returned (answers B and C are wrong). The servlet compiles just fine, invalidating answer A.
No output occurs because of the runtime error, invalidating answers B and C.
Although output has been committed (in line 14 - out.flush()), it is OK still to invoke include() method on a RequestDispatcher. Had this been the forward() method here, then the IllegalStateException mentioned in answer D would have occurred.
There is no reason for line 16 not to execute; it just doesn't influence the output (answer E).
Finally, answer F is meant to make you think this is the root cause of the compilation error (or perhaps gives rise to a runtime error). The opposite of the truth is stated here. A RequestDispatcher returned from ServletContext does require "/" at the beginning of the parameter to getRequestDispatcher. However, the opposite of this is not true: a RequestDispatcher returned from the Request can legitimately have "/" (or not) at the beginnng of the parameter to getRequestDispatcher.


EMail: dbridgewater@jbridge.co.uk
Phone: +44 (0)1943 877414
Fax: +44 (0)1943 877414
Mail: David Bridgewater, Willow Dene, Bradford Road, Menston, Ilkley, West Yorkshire, LS29 6ED, UK
Copyright © 2003 David Bridgewater. All rights reserved.