此页面上的问题询问如何从php页面运行java程序: Run Java class file from PHP script on a website
我想从JSP页面做同样的事情。我不想导入类和调用函数或类似的任何复杂的东西。我想做的就是运行如下命令: java测试 从JSP页面,然后通过Test保存在JSP页面中的变量中,将打印出来的内容输出到System.out。
我该怎么做?
非常感谢!!
答案 0 :(得分:1)
您可以通过Runtime.exec()
:
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 :(得分:0)
由于您已经运行了JVM,因此您应该能够通过使用jar实例化类加载器并反射性地找到main方法并调用它来完成它。
这是一些可能有帮助的样板:
// 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 });