• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HFJS (V2) Final Mock Question 45 is wrong?

 
Kay Li
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Given this fragment from a valid doGet() method:
12. OutputStream os = response.getOutputStream();
13. byte[] ba = {1,2,3};
14. os.write(ba);
15. RequestDispatcher rd = request.RequestDispatcher("my.jsp");
16. rd.forward(request, response);
Assuming that "my.jsp" adds the bytes 4, 5, and 6 to the response, what is the result?

A. 123
B. 456
C. 123456
D. 456123
E. An exception is thrown

Book's answer:
-Option B: because os.flush() wasn’t called, the uncommitted output (123), is cleared, and forward is invoked without exception. If os.flush() had been called before forward, an IllegalStateException would have been thrown.

my answer is E.
I tried in NetBeans IDE 6.1. If PrintWriter out = response.getWriter() is used instead of OututStream os = response.getOutputStream(), Option B would be the case.
When OututStream os = response.getOutputStream() is used, an Exception is thrown:

type Exception report
message
descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
exception
java.lang.IllegalStateException: PWC3991: getOutputStream() has already been called for this response

I think it is because JSP uses JSPWriter out implicit object.

Kay
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can't say much about your case because I have not tried it yet, but the Servlet specification says that you can write whatever content you like to the response writer or stream, as long as it is not flushed, before you forward. Considering that answer B is correct.
 
Chinmaya Chowdary
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kay. I tested this in Tomcat5.5.9. Here option E is correct.

Here there is syntax error also present
It should be
If it is then the container throws "java.lang.IllegalStateException", since the OutputStream already opened in the servlet class. There is only one OutputStream for any request.

If we use it will work fine.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic