0

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!!

Community
  • 1
  • 1
tree-hacker
  • 5,351
  • 9
  • 38
  • 39
  • why've I been downvoted? – tree-hacker Feb 22 '13 at 03:46
  • 3
    Because people on stack overflow are pretentious and think everything is a bad question. I voted your question back to 0 and am curious to see the answer myself. –  Feb 22 '13 at 03:59

2 Answers2

1

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();
ericson
  • 1,658
  • 12
  • 20
0

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 });
Niels Bech Nielsen
  • 4,777
  • 1
  • 21
  • 44