File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes How to get servlet's full path name Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "How to get servlet Watch "How to get servlet New topic

How to get servlet's full path name

Nicolas Tolksdorf

Joined: Nov 07, 2001
Posts: 5
What is the most effective way of getting a servlet's full/absolute path?
There is a getRealPath() method in the javax.servlet.ServletConfig interface but i'm not clear about how to implement this interface. Especially since an interface is abstract by definition and can't be instantiated.
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63854

You don't implement the servlet config interface.
An object that already implements that interface is available to you within any servlet via getServletConfig().
That said, what path are you really trying to discover? getRealPath() may not be the correct mechanism.
[ June 30, 2003: Message edited by: Bear Bibeault ]

[Asking smart questions] [About Bear] [Books by Bear]
Scott Duncan
Ranch Hand

Joined: Nov 01, 2002
Posts: 364
Not sure if this is what you want but:
this.getClass().getName() returns the fully qualified class name. If you want the name of a different servlet than the one currently being ran you can do this:
as long as the appropriate import statement is made to include MyServlet.

No more rhymes! I mean it!<br /> <br />Does anybody want a peanut?
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33111

In the HttpServletRequest object, there are two useful methods for this:
getServletPath() gives you the name of the servlet
getRequestURI() gives you the full path that was called

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Nicolas Tolksdorf

Joined: Nov 07, 2001
Posts: 5
Thanks for your help.
As i'm loading a properties file ( db name, db address, etc ) in an init() of my parent class. Getting the servlet to automatically discover the full path name to this file is useful as the servlet context changes between my live setup and development setup.
So i've used the getServletContext() method to get a ServletContext object and i was able to then get the full windows path of a folder within the servlet context:
ServletContext servletContext = getServletContext();
String strAbsolutePath = servletContext.getRealPath("properties");

Thanks again.
I agree. Here's the link:
subject: How to get servlet's full path name
It's not a secret anymore!