How can I get the path to the currently running servlet's .class file?

Luigi Viggiano

Try this piece of code, it does work even for standard Java objects:

        String className = servlet.getClass().getName();
        ClassLoader servletClassLoader = servlet.getClass().getClassLoader();
        URL classFileURL = servletClassLoader.getResource(className + ".class");
        System.out.println("classFileURL = " + classFileURL);
Where servlet is an instance of your servlet. [Note: from inside a running servlet, use this.getClass() -Alex]

If you don't have ready any instance of your servlet, you should replace Servlet.class where servlet.getClass() is used. [Note: this will return the path to Servlet.class, not to MyServlet.class -- Servlet.class may be stored in a totally separate directory, based on the Servlet engine. -Alex]