|
Recipe 7.11. Displaying a File from the ServerProblemYou need to display the contents of a file on your server's filesystem that isn't part of your web application. SolutionUse a servlet, similar to the one shown in Example 7-13, to read the file from the filesystem and write the file contents to the HTTP response. Example 7-13. File viewer servletpackage com.oreilly.strutsckbk.ch07; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class FileViewerServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String fileName = (String) request.getAttribute("fileName"); fileName = "temp.txt"; FileReader in = null; PrintWriter out = null; response.setContentType("text/plain"); File dir = (File) getServletContext( ).getAttribute("javax. servlet.context.tempdir"); File f = new File(dir, "test.tmp"); try { // Get an input stream on the form file in = new FileReader(f); // Get an output stream for the response out = response.getWriter( ); // Write from the input stream to the output stream char[] buffer = new char[512]; int chars = 0; while ((chars = in.read(buffer)) != -1) { out.write(buffer, 0, chars); } } finally { if (out != null) out.close( ); if (in != null) in.close( ); } } } DiscussionThis servlet reads a file from the filesystem and writes it out to the response; it's written to handle a file uploaded using the Solution from Recipe 7.10. The file is read from the servlet's temp directory; however, the location of the file could be any place accessible to the server, even a database.
Here are the primary steps to render content from a servlet, regardless of where the file is located:
See AlsoJason Hunter's classic text, Java Servlet Programming (O'Reilly), is the bible of servlet programming. This text has loads more information on the details and nuances of rendering content in this fashion. Recipe 6.5 shows a good technique for integrating a servlet like this into a Struts application. |
|