FileDocCategorySizeDatePackage
FileServlet.javaAPI DocExample1419Wed Apr 05 11:25:42 BST 2000None

FileServlet.java

/*
 * This example is from the book "Java Enterprise in a Nutshell".
 * Copyright (c) 1999 by O'Reilly & Associates.  
 * You may distribute this source code for non-commercial purposes only.
 * You may study, modify, and use this example for any purpose, as long as
 * this notice is retained.  Note that this example is provided "as is",
 * WITHOUT WARRANTY of any kind either expressed or implied.
 */

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class FileServlet extends HttpServlet {

  public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  
    File r; 
    FileReader fr;
    BufferedReader br;
    try {
      r = new File(req.getParameter("filename"));
      fr = new FileReader(r);
      br = new BufferedReader(fr);
      if(!r.isFile()) {  // Must be a directory or something else
        resp.sendError(resp.SC_NOT_FOUND);
        return;
      }
    } 
    catch (FileNotFoundException e) {
      resp.sendError(resp.SC_NOT_FOUND);
      return;
    }
    catch (SecurityException se) { // Be unavailable permanently
      throw(new UnavailableException(this, 
        "Servlet lacks appropriate privileges."));
    } 

    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    String text;
    while( (text = br.readLine()) != null)
      out.println(text);
    
    br.close();
  }
}