Unable to execute java program from jsp using Runt

2019-03-05 09:43发布

问题:

I am trying to run a jar file through jsp. I use the command Runtime.getRuntime().exec("java -jar file.jar"); I get the error Unable to access jarfile file.jar when I print the error stream.

I tried running with the classpath set to the current directory as Runtime.getRuntime().exec("java -cp . -jar file.jar"); but still get the same error. I also tried giving the entire path to the jar file. When I do this, the jsp file hangs after execuing the exec statement.

This is the line I use in windows:

process = Runtime.getRuntime().exec("java -jar C:\\Users\\Jeff\\Documents\\NetBeansProjects\\WebApplication1\\file.jar");

I use the streamgobbler thing given in the article but still have the same problem (hangs). Can someone help?

回答1:

It will never work. Otherwise it would be security breach. Imagine that you could run any executable from web browser... You should put your classes on server, make them accessible to your jsp and then run some method from jsp.



回答2:

Though it's better to add a jar to WEB-INF/lib and execute needed functionality using method call or at least move scriptlet code to a servlet, it's perfectly legal to use any functionality provided by Java in JSP scriptlets.

test.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>Test</title>
  </head>
  <body>
  <%
    try {
      Runtime runtime = Runtime.getRuntime();
      Process exec = runtime.exec(new String[]{"java", "-cp", "/home/test/test.jar", "Main"});
      int i = exec.waitFor();
      System.out.println(i);
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
  %>
  hi
  </body>
</html>

test.jar contains the following class:

Main.java

public class Main {

  public static void main(String[] args) {
    System.out.println('hello');
  }

}

This example runs fine. JSP prints 0 in a server output stream which means that no error has happened.

While you're developing webapp locally your machine is a server and a client at the same time. This thing can confuse you, so you have to understand that the code from jar file you are trying to run will be executed on a _server.

In your case the problem is caused by the code in jar file itself. Try to create a simple class and see if it works.