简体   繁体   English

无法从JSP启动.bat文件

[英]unable to start .bat file from JSP

I have a batch file runthis.bat 我有一个批处理文件runthis.bat

dir >dir.txt 目录> dir.txt

If I double click on this, a text file is being created with name dir.txt 如果我双击此文件,则将创建一个名为dir.txt的文本文件。

Now I have to run this batch file using JSP. 现在,我必须使用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? 可能是什么问题?

First, JSP is the wrong place for this. 首先,JSP是错误的地方。 Do it in a real Java class. 在真正的Java类中进行操作。 Start with a Servlet . Servlet开始。 Have a form with a button which submits to a servlet. 有一个带有按钮的表单,该表单提交给Servlet。 Put this code in the doPost() method. 将此代码放在doPost()方法中。 Let the servlet put the result in request scope and forward the request to a JSP. 让servlet将结果放入请求范围,并将请求转发到JSP。 Let the JSP display the result. 让JSP显示结果。

Second, learn the pitfalls of Runtime#exec() in this article . 第二,在本文中了解Runtime#exec()的陷阱。 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. 顺便说一下,这个问题与JSP无关。 You would face exactly the same problem when doing so in a normal Java class. 在普通的Java类中,您将面临完全相同的问题。

Try executing: 尝试执行:

cmd /c your.bat

That is: 那是:

run.exec("cmd /c C:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps/try/runthis.bat");

EDIT: 编辑:

And I would suggest you to be careful with spaces within the path. 我建议您在路径内的空格时要小心。 It would be great if you escaped them or wrapped the whole path with quotes (""). 如果您转义了它们或用引号(“”)括住了整个路径,那就太好了。

我猜你应该在路径中使用退格键:

run.exec("C:\\Program Files\\Apache Software Foundation\\Tomcat 5.5\\webapps\\try\\runthis.bat");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM