Serve binary content
Servlets usually serve some form of text - HTML, XML, plain text, and so on. Servlets can also serve binary content, such as images or .pdf files.
Here is 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 // 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"); ServletOutputStream output = aResponse.getOutputStream(); InputStream input = null; try { //serve a fixed file, located in the root folder of this web app input = getServletContext().getResourceAsStream("test.pdf"); //if raw bytes are already available, use this instead : //InputStream inputBytes = new ByteArrayInputStream(myBytes); //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); } } finally { //close all streams output.close(); if (input != null) input.close(); } log("Done."); } }
Would you use this technique?
|
|