There are several ways to do this. While the WAR file is expanding (a set of files instead of a single .war file), you can use this API:
ServletContext context = getContext(); String fullPath = context.getRealPath("/WEB-INF/test/foo.txt");
http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContext.html#getRealPath(java.lang.String)
This will give you the full system path to the resource you are looking for. However, this will not work if the Servlet container never expands the WAR file (for example, Tomcat). What will work using the ServletContext getResource methods.
ServletContext context = getContext(); URL resourceUrl = context.getResource("/WEB-INF/test/foo.txt");
or alternatively if you just want the input stream:
InputStream resourceContent = context.getResourceAsStream("/WEB-INF/test/foo.txt");
http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContext.html#getResource(java.lang.String)
The latter approach will work no matter which servlet container you use and where the application is installed. The first approach will only work if the WAR file is unpacked before deployment.
EDIT: The getContext () method should obviously be implemented. JSP pages make it available as a context field. In the servlet, you get it from your ServletConfig , which is passed to the init() servlet method. If you save it at this time, you can get your ServletContext anytime after that.
Berin Loritsch Dec 03 '10 at 3:05 2010-12-03 03:05
source share