June 12, 2011

Writing binary content to the HTTP response from a Servlet

The getWriter() method on the HttpServletResponse object returns a PrintWriter object which is used for writing text data to the response. When binary data has to be returned in the response (for example, a file download), the getOutputStream() method may be invoked on the response object. The following code example demonstrates the same.

1) Create the Servlet class in the src folder of the web application as follows,

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class BinaryResponseServlet extends HttpServlet{

   public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {


      InputStream is = getServletContext().getResourceAsStream("/WEB-INF/test.pdf");
      OutputStream outs = response.getOutputStream();

      int inByte = 0;
      while ((inByte = is.read()) != -1) {   


2) Configure the servlet in the web.xml file present in the WebContent/WEB-INF folder of the web application


3) Add the binary file (in this case any pdf file renamed as test.pdf) to the WebContent/WEB-INF folder of the web application.

4) Test the servlet by typing the following URL in the browser


No comments:

Post a Comment