import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.oreilly.servlet.ServletUtils;
public class ViewFile extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// Use a ServletOutputStream since we may pass binary information
ServletOutputStream out = res.getOutputStream();
// Get the file to view
String file = req.getPathTranslated();
// No file, nothing to view
if (file == null) {
file = getServletContext().getRealPath("/index.html");
}
// Get and set the type of the file
String contentType = getServletContext().getMimeType(file);
res.setContentType(contentType);
// Return the file
try {
ServletUtils.returnFile(file, out);
}
catch (FileNotFoundException e) {
log("Could not find file: " + e.getMessage());
res.sendError(res.SC_NOT_FOUND);
}
catch (IOException e) {
getServletContext().log(e, "Problem sending file");
res.sendError(res.SC_INTERNAL_SERVER_ERROR,
ServletUtils.getStackTraceAsString(e));
}
}
}
|