Referencing a file inside the .war file from a JSP

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?

    Requires Free Membership to View

    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

    By submitting your registration information to SearchSOA.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchSOA.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

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);
  }
%>

This was first published in June 2003