Deliver any kind of content via servlets

If you need to provide users on your site with dynamic content, servlets may be the answer. Learn a simple technique for using servlets to send data to users.

In the simplest case, downloading a file through a link on a Web page is easy to implement. But developers are often called upon to deliver dynamically created data or need to force users to agree to license terms and/or log in. In those situations, you need something a little smarter than a hyperlink to manage the delivery of your content—something like a servlet. Let's look at how you can use servlets to deliver data to a client.

What the browser needs to know
For a servlet to deliver an arbitrary binary file to a Web client, you have to follow a few steps in your servlet's doGet() or doPost() implementation. First, set the content type for the data you'll be sending to the user. Content types (properly called MIME types) are denoted by two words, separated by a slash, that will tell the browser what kind of data it will be receiving. For example, PDF documents use a content type of "application/pdf." Set the content type through the ServletResponse object (declared here as response):

Next, set the disposition information. This tells the browser how to handle the data and sets a filename for that data:

The inline portion of the header tells the browser client that it should display the data within the browser window, if possible. You can replace inline with attachment if you would prefer that the data be saved to disk or opened by an external program.

You can also optionally set the content length. This isn't required, but it helps increase the reliability of the data transfer:
response.setContentLength(/* insert int value here with
length of data in bytes */);

Finally, to send the data to the client, you'll need to get a reference to the OutputStream of the ServletResponse object and write your data to it:
ServletOutputStream outStream  =
out.write(/* use the appropriate OutputStream.write
methods to send your data bytes to the client */);

You can use this method to provide any sort of data to a client, whether it's a spreadsheet file or an image. It's a simple technique that should be in every servlet developer's bag of tricks.

Editor's Picks