O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

13.3. Sending an XML file

Problem

You want to send an XML file as binary data from a servlet.

Solution

Use the javax.servlet.ServletOutputStream obtained from the javax.servlet.http.HttpServletResponse object to send the XML file as binary data to the client.

Discussion

This recipe describes how to send an XML file as binary data from a ServletOutputStream, so that the user can handle the file as downloaded XML. Example 13-3 obtains the bytes that represent the XML as a BufferedInputStream wrapped around a FileInputStream. The code is very similar to Example 13-1 in Recipe 13.1, except that it uses a MIME type of text/XML.

Tip

In a popular form of converting XML into a readable format, you could convert the XML content to HTML or another form using Extensible Stylesheet Language Transformations (XSLT). If the intent is to use XSLT for generating the content in a browser, leave out the Content-Disposition response header, because this header is designed to handle the XML as a downloaded file that will be saved in the user's filesystem. See Chapter 23 on using the x:transform JSTL tag.

Example 13-3. Sending an XML file with a servlet

package com.jspservletcookbook; import java.io.FileInputStream; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import javax.servlet.*; import javax.servlet.http.*; public class SendXml extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required