如何从Tomcat应用程序的类路径获取所有jar?

时间:2015-04-25 13:07:13

标签: java tomcat jar classpath

我需要编写新模块,它能够在运行时获取所有应用程序的jar。

我尝试使用Classloader.getSystemClassloader()获取inforimation,但Tomcat中的catalina.bat覆盖了类路径的变量。

因此,接下来的想法是递归遍历所有目标文件夹并查找 lib 文件夹。在我的模块中,我写道:

public class MainServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        File currentDir = new File(getServletContext().getRealPath("/")); // current directory
        System.out.println("Cur dir: " + currentDir);
        displayDirectoryContents(currentDir);
    }
}

我得到了这个结果:

  

Cur dir:C:\ Java \ apache-tomcat-7.0.56 \ webapps \ jar

这是我战争的路径,我将其添加到应用程序中。但我需要应用程序本身的路径。

那么,你知道吗?

2 个答案:

答案 0 :(得分:4)

Java EE应用程序已自定义ClassLoader层次结构。

public class MainServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) {
        ClassLoader effectiveClassLoader = getClass().getClassLoader();
        URL[] classPath = ((URLClassLoader) effectiveClassLoader).getURLs();
        ...
    }
}

答案 1 :(得分:0)

您需要应用程序的类加载器,而不是Tomcat。获取servlet的类加载器 - this.getClass()。getClassLoader()或MainServlet.getClassLoader()都应该有效。