Tuesday, 22nd June 2010
The new frontier for learning Java

Output a binary stream from a JSP

From WikiJava

Jump to: navigation, search


This tutorial shows how to have a JSP returning a binary stream. This is useful when you want to output for example a pdf or an image.

Contents

the article

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.

<%@ 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.flush();
    o.close();// *important* to ensure no more jsp output
    return; 
%>

See Also

Real's Java How To

Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Title (required):

Website:

Comment: