The question on this page asks how to run a java program from a php page: Run Java class file from PHP script on a website
I want to do the exact same thing from a JSP page. I don't want to import the classes and call functions or anything complicated like that. All I want to do is run a command like: java Test from a JSP page and then get whatever is printed out to System.out by Test saved in a variable in the JSP page.
How do I do this?
Thanks a lot!!
You can do this via 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();
Since you already have a JVM running you should be able to do it by instantiating a classloader with the jars and reflectively find the main method and invoke it.
This is some boilerplate that may be helpful:
// 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 });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.