Rob Hazlewood wrote:

> Hi,
> I have a servlet, with a section of the filesystem as follows:
>
> lib/myservlet.jar
> etc/settings.txt
>
> before I packaged the jar, I was using getResourceAsStream to open the
> settings file. It now returns null
>
> getResourceAsStream("../../etc/settings.txt");
>
> The classpaths have changed, so I am wondering, can a class in a classpath
> open a resource that is in a higher level directory
> (the classpath is pointing to the jar)
> can I find out the location of the settings file to open with the filereader?
>

Trying to use getResource() or getResourceAsStream() like this is not going to be
portable, because you are trying to reference things outside the current web
application.  You also don't want to try using file I/O, because that precludes
you from running in servlet containers that do not expand your WAR file into a
directory.

There are two portable approaches to loading things like settings files for you
to consider:

(1) ServletContext.getResource() or ServletContext.getResourceAsStream()

A very useful place to store configuration files is in the WEB-INF subdirectory
of your web application (that is, in the same directory that you put the web.xml
file into.  For example, the Struts framework <http://jakarta.apache.org/struts>
assumes that your configuration file is at resource path "/WEB-INF/action.xml".

One very nice advantage of this location is that servlet containers are
prohibited from serving the contents of the WEB-INF directory as responses to a
client request.  Thus, you can store sensitive information (such as database
passwords) here without fear that someone will type:

    http://localhost:8080/myapplication/WEB-INF/action.xml

in their browser and see what settings you have defined.

(2) Class.getResource() and Class.getResourceAsStream()

This approach is best for resource files that are part of your application
itself, and are not necessarily designed to be overridden by whoever is
installing your application.  These calls work even if your class is in a JAR
file -- the resource is expected to be in the same JAR file.

>
> thanks
> Rob
>

Craig McClanahan

====================
See you at ApacheCon Europe <http://www.apachecon.com>!
Session VS01 (23-Oct 13h00-17h00):  Sun Technical Briefing
Session T06  (24-Oct 14h00-15h00):  Migrating Apache JServ
                                    Applications to Tomcat

___________________________________________________________________________
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff SERVLET-INTEREST".

Archives: http://archives.java.sun.com/archives/servlet-interest.html
Resources: http://java.sun.com/products/servlet/external-resources.html
LISTSERV Help: http://www.lsoft.com/manuals/user/user.html

Reply via email to