首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从JSP页面运行java应用程序

问从JSP页面运行java应用程序
EN

Stack Overflow用户
提问于 2013-02-22 11:45:01
回答 2查看 2.4K关注 0票数 0

本页上的问题是如何从php页面运行java程序:Run Java class file from PHP script on a website

我想在JSP页面中执行完全相同的操作。我不想导入类和调用函数或任何类似的复杂操作。我所要做的就是从JSP页面运行类似于: java Test的命令,然后将Test打印到System.out的内容保存到JSP页面的变量中。

我该怎么做呢?

非常感谢!

EN

回答 2

Stack Overflow用户

发布于 2013-02-22 13:27:37

您可以通过Runtime.exec()完成此操作

代码语言:javascript
复制
Process p = Runtime.getRuntime().exec("java Test");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = input.readLine();
while (line != null) {
  // process output of the command
  // ...
}
input.close();
// wait for the command complete
p.waitFor();
int ret = p.exitValue();
票数 1
EN

Stack Overflow用户

发布于 2013-02-22 21:41:00

由于您已经有了一个正在运行的JVM,因此您应该能够通过使用jars实例化一个类加载器来执行此操作,并反射地找到main方法并调用它。

这是一些可能有帮助的样板文件:

代码语言:javascript
复制
    // add the classes dir and each file in lib to a List of URLs.
    List urls = new ArrayList();
    urls.add(new File(CLASSES).toURL());
    for (File f : new File(LIB).listFiles()) {
        urls.add(f.toURL());
    }

    // feed your URLs to a URLClassLoader
    ClassLoader classloader =
            new URLClassLoader(
                    urls.toArray(new URL[0]),
                    ClassLoader.getSystemClassLoader().getParent());

    // relative to that classloader, find the main class and main method
    Class mainClass = classloader.loadClass("Test");
    Method main = mainClass.getMethod("main",
            new Class[]{args.getClass()});

    // well-behaved Java packages work relative to the
    // context classloader.  Others don't (like commons-logging)
    Thread.currentThread().setContextClassLoader(classloader);

    // Invoke with arguments
    String[] nextArgs = new String[]{ "hello", "world" }
    main.invoke(null, new Object[] { nextArgs });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15016461

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档