views:

49

answers:

1

I am writing a Java servlet, using Tomcat as the container, which creates and serves PDF files to the end-user. Currently the PDF files are created in-memory and written out as a response to a POST.

I would like to change this up somewhat so that the PDF files are written to disk (so they can be served up again later). I am having trouble locating a suitable "how-to" for doing this.

How can I configure my servlet to write to and read files from a directory server-side? From what I've read, I think I need to locate this directory somewhere outside where my "exploded webapp" lives in $CATALINA_BASE for security reasons, and I need to use a Context or somesuch.

+3  A: 

You can just use the usual FileOutputStream and FileInputStream classes to respectively write to and read from the disk. Change your PDF generator to write to FileOutputStream and change your file servlet to read from FileInputStream.

And, indeed, you'd like to store those files outside the webapp, else it will all get lost whenever you redeploy the webapp. You don't need the ServletContext, it's only useful to convert a relative web path to an absolute disk file system path. You don't need it when you're storing it outside the webapp, you namely already know the absolute disk file system path.

See also

BalusC
I'll have a look at your FileServlet example code right now. Quick follow up question: should I implement the file serving aspect as a separate servlet? (I'm not sure what Servlet best practices are here, but I kind of like the idea since it seems like a nice separation with the code that creates the PDF.)
Shaggy Frog
You can do so. It makes the code reuseable for other purposes than generating/serving PDF files. The PDF servlet in turn can best be modified to check if the PDF file is already generated and if so, then forward to the fileservlet. If not, then generate one and then forward to fileservlet.
BalusC
Belated thank you. Your Web site is a treasure trove of Java goodness.
Shaggy Frog
You're welcome :)
BalusC