Serve binary content

Servlets usually serve some form of text - HTML, XML, JSON data, plain text, and so on. Servlets can also serve binary content, such as images or .pdf files.

Here's an example of a simple servlet that serves binary content. It serves a .pdf file of a fixed name, located in the web application's root directory.

import java.io.*;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 Servlet that serves binary data, not text.
  
 <P>This servlet serves a static .pdf file, but the idea is the same with other 
 forms of data.
*/
public class ServeBinary extends HttpServlet {

  @Override protected void doGet(
    HttpServletRequest aRequest, HttpServletResponse aResponse
  ) throws ServletException, IOException {
    serveBinary(aRequest, aResponse);
  }
   
  @Override protected void doPost(
    HttpServletRequest aRequest, HttpServletResponse aResponse
  ) throws ServletException, IOException {
    serveBinary(aRequest, aResponse);
  }
  
  // PRIVATE

  //elided...
  
  private void serveBinary(
    HttpServletRequest aRequest, HttpServletResponse aResponse
  ) throws IOException {
    log("ServeBinary servlet.");
   
    //IMPORTANT: set the MIME type of the response stream
    aResponse.setContentType("application/pdf");
    
    //serve a fixed file, located in the root folder of this web app 
    try (
      ServletOutputStream output = aResponse.getOutputStream();
      InputStream input = getServletContext().getResourceAsStream("test.pdf");
    ){ 
      //transfer input stream to output stream, via a buffer
      byte[] buffer = new byte[2048];
      int bytesRead;    
      while ((bytesRead = input.read(buffer)) != -1) {
         output.write(buffer, 0, bytesRead);
      }
    }
    
    log("Done.");
  }
}