0

このページの質問は、php ページから Java プログラムを実行する方法を尋ねています: Run Java class file from PHP script on a website

JSPページからまったく同じことをしたい。クラスをインポートして関数を呼び出したり、そのような複雑なことはしたくありません。私がやりたいことは、JSP ページから java Test のようなコマンドを実行し、JSP ページの変数に保存された Test によって System.out に出力されるものを取得することだけです。

どうすればいいですか?

どうもありがとう!!

4

2 に答える 2

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();
于 2013-02-22T05:27:36.913 に答える
0

すでにJVMを実行しているので、jarを使用してクラスローダーをインスタンス化し、反射的にmainメソッドを見つけて呼び出すことで、JVMを実行できるはずです。

これは役立つかもしれないいくつかの定型文です:

    // 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 });
于 2013-02-22T13:41:00.037 に答える