The path to the resource in our folder war / WEB-INF?

I have a file in my war / WEB-INF folder of my application engine project. I read in frequently asked questions that you can read from there in the context of a servlet. I do not know how to form the path to the resource, though:

/war/WEB-INF/test/foo.txt 

How do I create my path to this resource for use with File (), as it looks above?

thank

+89
java google-app-engine web-applications
Dec 02 '10 at 22:28
source share
3 answers

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.

+134
Dec 03 '10 at 3:05
source share

Now with Java EE 7 you can easily find a resource using

 InputStream resource = getServletContext().getResourceAsStream("/WEB-INF/my.json"); 

https://docs.oracle.com/javaee/7/api/javax/servlet/GenericServlet.html#getServletContext--

+2
Jul 11 '17 at 18:18
source share

I know it's late, but thatโ€™s what I usually do,

 ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream stream = classLoader.getResourceAsStream("../test/foo.txt"); 
0
Jul 09 '19 at 6:54
source share



All Articles