FileDocCategorySizeDatePackage
UrlServlet.javaAPI DocExample2360Tue May 13 13:17:44 BST 2003com.jspservletcookbook

UrlServlet

public class UrlServlet extends HttpServlet

Fields Summary
Constructors Summary
Methods Summary
public voiddoGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)

    
      //get the file name 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 UrlServlet servlet.");
      
      // add the .pdf suffix if it doesn't already exist
      if (fileName.indexOf(".pdf") == -1)
          fileName = fileName + ".pdf";
    	  
      URL pdfDir = null;
      URLConnection urlConn = null;
      ServletOutputStream stream = null;
      BufferedInputStream buf = null;
     try{
     
        //where are PDFs kept? remote-pdf-dir=http://www.jspservletcookbook.com/downloads/
    pdfDir = new URL(getServletContext().getInitParameter("remote-pdf-dir") + fileName);
    
    } catch (MalformedURLException mue){
    
           throw new ServletException(mue.getMessage());
   }
   try{
          
     stream = response.getOutputStream();
    
      //set response headers
      response.setContentType("application/pdf");
      response.addHeader(
        "Content-Disposition","attachment; filename="+fileName );
      
      urlConn = pdfDir.openConnection();
      response.setContentLength( (int) urlConn.getContentLength()  );
     
     buf = new BufferedInputStream(urlConn.getInputStream());
     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();
          }
    
    
public voiddoPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)

        
        doGet(request,response);