[ Back | Previous | Next ]

How to send binary data to the client with HttpServlet?

Package:
javax.servlet.*
Product:
JSDK
Release:
1.1.x
Related Links:
General
General
General
General
General
Comment:

If you use the standard Java Server Development Kit how can you send response if it is an images or data which is not html. There are two ways with the HttpServlet class;

  1. sendRedirect
  2. send the data or images on the outputstream
The sendRedirect can only handle URL's and can be used as follows
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * This is a basic redirection servlet.  It takes a single
 * destination, which it then redirects the browser to... Useful
 * for logging how many times links off of your site are used.
 * Example: http://www.mysite.com/RedirectServlet?http://anothersite.com/
 */
public class RedirectServlet extends HttpServlet { 

/**
 * Given a request with either extra path info or a QueryString, redirect
 * browser to appropriate site.
 * @param req Request object the servlet uses to get input.
 * @param res Response object that the servlet uses to send output.
 * @exception ServletException @see HttpServlet
 * @exception IOException occurs due to general network errors.
 */
    public void service(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    {
        String location = "http://mysite.com/index.html";
         res.sendRedirect(location);

    }
 
The other way is to send the image or data over the outputstream as a binary.
We instruct the client by sending two parameters to the client
  1. the mime-type and (see link )
  2. the length of the binary data over the stream (see link )
class ... extends HttpServlet {

    public synchronized void doGet (HttpServletRequest req, HttpServletResponse res)    
    throws ServletException, IOException {
        File dot_clearImage = null;
        ServletOutputStream out = null;
        
        // MessageFormat necesety
        http = req;

        http = req;
        // set file and sending file to the client
        try {
          
          File dot_clearImage = new File( "dot_clear.gif" );

          // if not exists abort
          if ( dot_clearImage.exists() ) {
            res.setContentType("image/gif");
            RandomAccessFile raf = new RandomAccessFile( dot_clearImage, "r" );
            res.setContentLength( (int) raf.length() );
            out = res.getOutputStream();
            
            byte [] loader = new byte [ (int) raf.length() ];
            while ( (raf.read( loader )) > 0 ) {
              out.write( loader );
            }
            //
            log("");
          } 
          else {
            System.out.println("Aborting: File doesn't exists, " + dot_clearImage + ", " + dot_clearPath + File.separator + dot_clearName  +
                 "abspath: " + dot_clearImage.getAbsolutePath() );
          }
          
        } catch (IOException ioe) {
          System.out.println("Unable to open Image file "); ioe.printStackTrace();
        } finally {
          if (out != null) {
            out.flush();
            out.close();
          }
        }

        // set content type and other response header fields first
        res.setContentType("text/html");

        // then write the data of the response
        if ( out == null ) {
          out = res.getOutputStream();
          out.println(" SimpleServlet Output ");
                out.println("

SimpleServlet Output

"); out.println("

This is output from SimpleServlet."); out.println(""); out.close(); } //destroy(); }

1