Recipe 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 .

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 {           //get the filename from the "file" parameter      String fileName = (String) request.getParameter("file");      if (fileName == null  fileName.equals(""))            throw new ServletException(             "Invalid or non-existent file parameter in SendXml servlet.");             // add the .xml suffix if it doesn't already exist      if (fileName.indexOf(".xml") == -1)           fileName = fileName + ".xml";                 //where are XML files kept?  String xmlDir = getServletContext( ).getInitParameter("xml-dir");      if (xmlDir == null  xmlDir.equals(""))            throw new ServletException(              "Invalid or non-existent xmlDir context-param.");  ServletOutputStream stream = null;      BufferedInputStream buf = null;      try{                stream = response.getOutputStream( );          File xml = new File(xmlDir + "/" + fileName);  //set response headers          response.setContentType("text/xml");  response.addHeader(             "Content-Disposition","attachment; filename="+fileName );          response.setContentLength( (int) xml.length( ) );                 FileInputStream input = new FileInputStream(xml);          buf = new BufferedInputStream(input);          int readBytes = 0;          //read from the file; write to the ServletOutputStream          while((readBytes = buf.read( )) != -1)             stream.write(readBytes);      } catch (IOException ioe){               throw new ServletException(ioe.getMessage( ));                } finally {                //close the input/output streams          if(stream != null)              stream.close( );          if(buf != null)              buf.close( );       }//finally        } //end doGet       public void doPost(HttpServletRequest request,      HttpServletResponse response)       throws ServletException, IOException {                  doGet(request,response);   }  } 

For the context-param to work correctly in this code, you have to include in web.xml an element that looks like:

 <context-param>     <param-name>xml-dir</param-name>     <param-value>h:/home/xml</param-value> </context-param> 

See Chapter 1 if you need an introduction or refresher for the deployment descriptor web.xml .


The discussion in Recipe 13.1 describes the basic mechanics of this code, so I don't repeat that information here. See the note at the end of Recipe 13.1 about the Internet Explorer- related exception that you may experience with servlets of this type.

See Also

Recipe 13.1 on sending a PDF file; Recipe 13.2 on sending a Microsoft Word file as binary data; Recipe 13.4 on sending MP3 files as binary data; Recipe 13.5 on getting an input stream representing a web resource such as web.xml ; the RFC technical documents on MIME: ftp://ftp.rfc-editor.org/in-notes/rfc2045.txt and ftp://ftp.rfc-editor.org/in-notes/rfc2046.txt; RFC 2183 at ftp://ftp.rfc-editor.org/in-notes/rfc2183.txt for background information on the Content-Disposition header; the Media Types section of the HTTP Pocket Reference by Clinton Wong (O'Reilly); Chapter 1 introducing the development of a servlet; a tutorial on java.sun.com on XSLT: http://java.sun.com/ webservices /docs/1.1/tutorial/doc/JAXPXSLT.html#wp68287.



Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net