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 {

      response.setContentType("application/pdf");

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

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

      outs.flush();
      outs.close();
      is.close();
   }
}


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

<servlet>
    <servlet-name>binaryResponse</servlet-name>
    <servlet-class>info.icontraining.servlets.BinaryResponseServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>binaryResponse</servlet-name>
    <url-pattern>/downloadFile</url-pattern>
</servlet-mapping>


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

http://localhost:8080/WebAppName/downloadFile

No comments:

Post a Comment