Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
938 views
in Technique[技术] by (71.8m points)

java - unable to start .bat file from JSP

I have a batch file runthis.bat

dir >dir.txt

If I double click on this, a text file is being created with name dir.txt

Now I have to run this batch file using JSP.

<%
Runtime run =Runtime.getRuntime();
run.exec("C:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps/try/runthis.bat");
out.println("SUCCESS");
%>

I'm getting the output SUCCESS on a webpage but this batch file is not running.

Whats might be the problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, JSP is the wrong place for this. Do it in a real Java class. Start with a Servlet. Have a form with a button which submits to a servlet. Put this code in the doPost() method. Let the servlet put the result in request scope and forward the request to a JSP. Let the JSP display the result.

Second, learn the pitfalls of Runtime#exec() in this article. Your problem is that you aren't checking the result nor the error stream (and thus never knows if the program executed successfully) and that you are expecting that it somehow runs in sync with your coding (while it actually runs in a separate thread/process). You're basically doing a "fire and forget", the code is basically not tracking the execution/termination of the program in any way.

This problem has by the way nothing to do with JSP. You would face exactly the same problem when doing so in a normal Java class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...