Skip to Main Content
Jakarta Struts Cookbook
book

Jakarta Struts Cookbook

by Bill Siggelkow
February 2005
Intermediate to advanced content levelIntermediate to advanced
528 pages
12h 53m
English
O'Reilly Media, Inc.
Content preview from Jakarta Struts Cookbook

7.11. Displaying a File from the Server

Problem

You need to display the contents of a file on your server's filesystem that isn't part of your web application.

Solution

Use 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 servlet

package 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; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Jakarta Struts

Programming Jakarta Struts

Chuck Cavaness
Beginning Spring Framework 2

Beginning Spring Framework 2

Bruce Snyder, Sing Li, Anne Horton, Thomas Van de Velde, Naveen Balani, Christian Dupuis
Java Cookbook

Java Cookbook

Ian F. Darwin
Struts 2 in Action

Struts 2 in Action

J. Scott Stanlick, Chad Michael Davis, Donald J. Brown

Publisher Resources

ISBN: 059600771XSupplemental ContentErrata Page