Tutorials4u.net Forum
Output a binary stream from a JSP - Printable Version

+- Tutorials4u.net Forum (http://www.tutorials4u.net/forum)
+-- Forum: Discussion Forum (/forumdisplay.php?fid=1)
+--- Forum: JSP (/forumdisplay.php?fid=3)
+--- Thread: Output a binary stream from a JSP (/showthread.php?tid=36)

Output a binary stream from a JSP - tutorials4u - 12-15-2010 01:34 AM

You can't.

From JSP, only character stream should be used.

JSP pages were designed for *text* output. The "out" object is a Writer, which means it will play games with text encoding.

For binary output, like PDF or dynamically generated GIF, it's a better idea to use a servlet.

Having said that, since a JSP will be converted to a servlet, it's possible to modifed the output stream.

You must be careful to format your JSP to emit no whitespace


<%@ page import="java.io.*" %>
<%@ page import="java.net.*" %>
<%@page contentType="image/gif" %><%
OutputStream o = response.getOutputStream();
InputStream is =
new URL("http://myserver/myimage.gif").getInputStream();
byte[] buf = new byte[32 * 1024]; // 32k buffer
int nRead = 0;
while( (nRead=is.read(buf)) != -1 ) {
o.write(buf, 0, nRead);
o.close();// *important* to ensure no more jsp output

Thanks to Benjamin Grant for the bug fix.

There is a trimWhiteSpaces directive that should help to remove the whitespaces form the generated JSP.

In your JSP code :

<%@ page trimDirectiveWhitespaces="true" %>

Or in the jsp-config section your web.xml


If you really have a required space in the generated JSP then you need use the HTML non-breaking space entity : &nbsp; .