Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

OutputStream in Jsp

 
Abir Majumder
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<%
OutputStream os = response.getOutputStream();
os.print("test".getBytes());
%>
a. The code will print the ascii values of the string 'test' to the Browser.
b. The program won't compile because of compilation errors.
c. The program will throw a run-time IllegalStateException.
d. The code will print 'test' in the Browser window.

I think the ans is b - OutputStream has no method as print.
But the ans is c.
The code will throw a Run-time exception, as it is not possible to call both the getWriter()
and getOutputStream() method on the same response object. Remember that for a JSP
page, the method getWriter() would have been called already by the Container and will be
stored in the 'out' variable.

Please comment.
Thanks
 
Aum Tao
Ranch Hand
Posts: 210
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are better off using a Servlet rather than a JSP here since "out" is already set by the JSP compiler by getting a Writer from the response stream.
 
Deepak Jain
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes thats correct.

Within a JSP you cannot invoke getWriter() and getOutputStream().

getWriter() javadoc:
Either this method or getOutputStream() may be called to write the body, not both.
java.lang.IllegalStateException - if the getOutputStream method has already been called for this response object

getOutputStream: javadoc:
Either this method or getWriter() may be called to write the body, not both.java.lang.IllegalStateException - if the getWriter method has been called on this response


Hence one thing is clear that either one of them must be called and not both.

Now when you write a JSP , JSP has a implicit object named out which gets intialized as
PrintWriter out = response.getWriter();

Now in your JSP if you have
<%
OutputStream os = response.getOutputStream();
os.print("test".getBytes());
%>

Have a look at the _jspService() of the generated servlet and you will see

PrintWriter out = response.getWriter();
OutputStream os = response.getOutputStream();

Hence you will see an exception IllegalStateException thrown by getOutputStream()
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic