本页上的问题是如何从php页面运行java程序:Run Java class file from PHP script on a website
我想在JSP页面中执行完全相同的操作。我不想导入类和调用函数或任何类似的复杂操作。我所要做的就是从JSP页面运行类似于: java Test的命令,然后将Test打印到System.out的内容保存到JSP页面的变量中。
我该怎么做呢?
非常感谢!
发布于 2013-02-22 13:27:37
您可以通过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();发布于 2013-02-22 21:41:00
由于您已经有了一个正在运行的JVM,因此您应该能够通过使用jars实例化一个类加载器来执行此操作,并反射地找到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 });https://stackoverflow.com/questions/15016461
复制相似问题