JSPWriter and PrintWriter objects in JSP
- JSP pages have access to the out object. This allows your
jsp
code (and bean code) to write directly to the browser page,
eliminating
the need for expression tags <%= %>.
- Using the out object makes your code more readable and saves
development
time.
- out is an instance of the javax.servlet.jsp.JspWriter
class and provides the same print and println functions that a
PrintWriter
has.
- There are differences though,
- JspWriters (unlike PrintWriters) will throw IOExceptions.
- JspWriters perform buffering, that is, your prints and printlns
are
buffered on the server and sent in blocks to the client stations.
- out is setup to do the
block sending (flushing of buffers) automatically.
You can turn this off and control when the blocks are sent to the
client
yourself.
- Example: Write the numbers from 1 to 100, one per line, to the
browser
(<br> is the html line break tag)
<%
//
// example using expression tags
//
for(int i = 1; i <= 100; i++)
{
%>
<%= i+""> <br>
<% } %>
<%
//
// example using the out object
//
for(int i = 1; i <= 100; i++)
{
out.println(i+"<br>");
}
%>
- Some standard Java functions require the use of PrintWriters.
If
you want to use these functions you can create a PrintWriter object
based
on the out object.
java.io.PrintWriter pw = new
java.io.PrintWriter(out);