*
The moose likes Servlets and the fly likes Reading file from a servlet packaged in war Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Reading file from a servlet packaged in war" Watch "Reading file from a servlet packaged in war" New topic
Author

Reading file from a servlet packaged in war

Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8904

Hi,
Is it possible to read a file packaged in a war file from a servlet class that is also packaged in the same war file. If yes how do I specify the path of the file?
Thanx in adv


Groovy
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 15959
    
  19

This is a variant of a popular question around here.
The problem is that you're assuming that the appserver works with WARs. Actually, a J2EE appserver (and really, Java in general) isn't expected to CARE where its classes and resources came from - if, in fact they were ever even in files to begin with - much less packages in an archive file.
When you invoke a Java classloader (as the appserver is doing), you are actually simply requesting that it return a class/resource from WHEREVER it can find it. And while that CAN be a ".class" file or component of a WAR (or EAR or JAR), it might just as easily have been magically conjured up from a parallel universe. Even though YOU know where it came from, the class loading mechanism isn't allowed to make that assumption.
So the short answer is "no". The ACTUAL answer is, "yes" - IF: 1, you embed it in a class; 2, you place it in a properties file; 3, you resort to some sort of gimmick like retrieving the file in the same way properties files are (by requesting them through the classloader); 4, you place the file in the content area of the WAR (where the JSP's are) and do an internal server request.
All of the above solutions are only good if the file is read-only. For read/write access, you can only reliably locate the file by passing its location as an absoute path to a startup servlet or some similar mechansim that makes that value accessible to the web application.
[ April 23, 2002: Message edited by: Tim Holloway ]

Customer surveys are for companies who didn't pay proper attention to begin with.
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8904

Hi,
It is possible to read a file by using
getServletContext().getResourceAsStream("/WEB-INF/web.xml"); which will return an InputStream object from which u can read the file.
 
jQuery in Action, 2nd edition
 
subject: Reading file from a servlet packaged in war
 
Similar Threads
Problem with packaging and deploying
.war file across platform/container?
JEE5 bean and war deployment
EJB Lookup Fails from JSP
Deploying My project in Jboss server