Referencing a file inside the .war file from a JSP
Can I reference a file - say a .pdf file - that exists inside my .war file
from a JSP? How would I do that? What is the relative path I would use?
When you register, you'll begin receiving targeted emails from my team of award-winning writers. Our goal is to keep you informed on recent service-oriented architecture (SOA) and SOA-related topics such as integration, governance, Web services, Cloud and more.
Hannah Smalltree, Editorial Director
You certainly can. The code snippet below will retrieve the size of a file named "myreport.pdf" from a directory named "resources" that resides directly under the "classes" directory under the WEB-INF directory of a typical Web application. The stipulation implied here is that the file must exist in a directory which is relative to the classpath. The WEB-INF\classes directory is always in the classpath. In order to reference another directory in the classpath, use the Class-Path: header field for the .war file. This is documented nicely at:
http://java.sun.com/docs/books/tutorial/jar/basics/manifest.html
<%@ page import="java.io.InputStream"%>
<p>
<%
try
{
InputStream inStream =
getClass().getResourceAsStream("/resources/myreport.pdf");
out.println("<p>File size == " + inStream.available());
inStream.close();
}
catch (Exception e)
{
out.println(e);
}
%>
Dig Deeper
-
People who read this also read...
This was first published in June 2003