Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've got a file in my war/WEB-INF folder of my app engine project. I read in the FAQs that you can read a file from there in a servlet context. I don't know how to form the path to the resource though:

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

How would I construct my path to that resource to use with File(), just as it looks above?

Thanks

like image 526
user291701 Avatar asked Dec 02 '10 22:12

user291701


People also ask

Where is WEB-INF folder?

WEB-INF. This directory, which is contained within the Document Root, is invisible from the web container. It contains all resources needed to run the application, from Java classes, to JAR files and libraries, to other supporting files that the developer does not want a web user to access.

What kind of files should be put under Folder WEB-INF?

You should put in WEB-INF any pages, or pieces of pages, that you do not want to be public.

How do you specify a resource path in Java?

The simplest approach uses an instance of the java. io. File class to read the /src/test/resources directory by calling the getAbsolutePath() method: String path = "src/test/resources"; File file = new File(path); String absolutePath = file.


1 Answers

There's a couple ways of doing this. As long as the WAR file is expanded (a set of files instead of one .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)

That will get you the full system path to the resource you are looking for. However, that won't work if the Servlet Container never expands the WAR file (like Tomcat). What will work is using the ServletContext's 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 what Servlet Container you use and where the application is installed. The former approach will only work if the WAR file is unzipped before deployment.

EDIT: The getContext() method is obviously something you would have to implement. JSP pages make it available as the context field. In a servlet you get it from your ServletConfig which is passed into the servlet's init() method. If you store it at that time, you can get your ServletContext any time you want after that.

like image 71
Berin Loritsch Avatar answered Sep 23 '22 13:09

Berin Loritsch