Can't execute java program from jsp with Runtime.getRuntime (). Exec
I am trying to run a jar file via jsp. I am using the command Runtime.getRuntime().exec("java -jar file.jar");
I am getting an error Unable to access jarfile file.jar
while printing the error stream.
I tried working with class pool set in current directory like Runtime.getRuntime().exec("java -cp . -jar file.jar");
, but still getting the same error. I have also tried giving the entire path to the jar file. When I do this, the jsp file hangs after executing the exec statement.
This is the line I am using on windows:
process = Runtime.getRuntime().exec("java -jar C:\\Users\\Jeff\\Documents\\NetBeansProjects\\WebApplication1\\file.jar");
I am using the streamgobbler thing mentioned in the article but still has the same problem (hangs). Can anyone help?
source to share
While it is best to add the jar to WEB-INF/lib
and execute the required functionality with a method call, or at least move the script code into a servlet, it is perfectly legal to use any of the functionality Java provides 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 works fine. The JSP prints 0
to the server's output stream, which means no error has occurred.
During webapp development locally, your machine is both a server and a client at the same time. This may confuse you, so you need to understand that the code from the jar file you are trying to run will be executed on the _server.
In your case, the problem is caused by code in the jar file. Try creating a simple class and see if it works.
source to share