Executing external Java program from a webapp

2019-08-30 01:26发布

问题:

I am trying to call an external Java class file from a servlet running on Tomcat 6, Windows 7, 64bit . There are already some threads on this subject around, but none are really helping me.

Fyi, I have successfully been able to do this if I run it from the shell directly.

Im using a ProcessBuilder to execute the command like this

 ProcessBuilder bp = new ProcessBuilder("cmd.exe","/C","java", "TheExternalClass", "ParameterA" });

I'm also consuming the errorStream and inputStream from the created Process.

When I run it from the servlet it simply stalls.

If I for example swith the java command to dir it does work as expected, leading me to believe it has something to do with either memory, or issues starting up a new Java Process from Tomcat or something like that.

Anybody has a pointer or a good idea on how to solve this?

Some other posts on the topic:

http://www.javaworld.com/jw-12-2000/jw-1229-traps.html?page=1

call a java program from a webapp in tomcat server - the java program is out side of tomcat server

Tomcat fails to execute external java program

Thanks much for reading.

回答1:

The code above works and it doesn't stall your servlet. My guess is that you call p.waitFor() or similar later or that you read the output streams of the process in the JSP thread - and that will block.

If you don't want to block, you have two options:

  • Use AJAX to poll the JSP in the background. The JSP will still block but the browser will be usable.
  • Create a background thread that reads the output streams. That will make the JSP return immediately but you will have to find a way to send the process results to the browser because it won't know what happens on the server.