Unable to execute java program from jsp using Runtime.getRuntime().exec

隐身守侯 提交于 2019-12-02 10:02:23

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!