【发布时间】:2011-10-10 18:18:25
【问题描述】:
我正在尝试从 tomcat 7 上的 java servlet 调用 perl 脚本。我已经设置了 context.xml 和 web.xml,因此我可以通过转到 http://localhost:8080/test/cgi-bin/test.pl 来运行 .pl 文件,我可以也可以直接在 java 中运行 perl,如下所示:
String[] cmdArr = new String[]{"perl", "-e", "print \"Content-type: text/html\n\n\";$now = localtime();print \"<h1>It is $now</h1>\";"};
if (cmdArr != null) {
Process p = null;
Runtime rt = Runtime.getRuntime();
try {
p = rt.exec(cmdArr); // throws IOException
returnValue = p.waitFor(); // throws InterruptedException
}
catch (IOException xIo) {
throw new RuntimeException("Error executing command.",xIo);
}
catch (InterruptedException xInterrupted) {
throw new RuntimeException("Command execution interrupted.",xInterrupted);
}
InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader stdout = null;
stdout = new BufferedReader(isr);
String line = null;
try {
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
}
catch (IOException xIo) {
throw new RuntimeException("Error reading process output", xIo);
}
}
这很好用,但是如果我尝试通过替换以下内容来引用我的 /WEB-INF/cgi 文件夹中的 .pl 脚本:
String[] cmdArr = new String[]{"perl", "-e", "print \"Content-type: text/html\n\n\";$now = localtime();print \"<h1>It is $now</h1>\";"};
类似:
String cmdArr = "/WEB-INF/cgi/test.pl";
或
String cmdArr = "/cgi-bin/test.pl";
我不断收到此错误:
java.io.IOException: Cannot run program "/WEB-INF/cgi/test.pl": error=2, No such file or directory
我猜我在某个地方的文件路径出错了?任何帮助将不胜感激!
更新:
在@hobbs 评论后我改为:String[] cmdArr = new String[]{"perl", "/WEB-INF/cgi/test.pl"};
但如果我在 .waitFor() 之前添加以下内容:
BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line;
while ( (line = br.readLine()) != null){
System.out.println(line);
}
我得到了打印:
Can't open perl script "/WEB-INF/cgi/test.pl": No such file or directory
我猜这又回到了原来的问题?
【问题讨论】:
标签: java perl servlets tomcat7