Send XML to client using Servlet : XML Word PDF Mp3 « Servlet « Java Tutorial






import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.text.DateFormat;
public class MyServlet extends HttpServlet {
   
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
      String fileName = (String) request.getParameter("file");
      if (fileName == null || fileName.equals(""))
           throw new ServletException(
            "Invalid or non-existent file parameter in SendXml servlet.");
      
      if (fileName.indexOf(".xml") == -1)
          fileName = fileName + ".xml";
          
     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);
     
      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 {
     
     if(stream != null)
         stream.close();
      if(buf != null)
          buf.close();
          }
    
    }
   
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        doGet(request,response);
    } 
}
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
    <servlet><servlet-name>MyServletName</servlet-name>
             <servlet-class>MyServlet</servlet-class>

             
    </servlet>
    
    <servlet-mapping><servlet-name>MyServletName</servlet-name>
        <url-pattern>/index.html</url-pattern>
    </servlet-mapping>
</web-app>
  Download:  ServeltSendXML.zip( 89 k)








25.31.XML Word PDF Mp3
25.31.1.Send Word file to client in a Servlet
25.31.2.Send MP3 file back to client with Servlet
25.31.3.Send XML data to client
25.31.4.Display PDF based on Request Parameter
25.31.5.Send XML to client using Servlet
25.31.6.Send Pdf to client using Servlet
25.31.7.Use XPath in servlet