gpt4 book ai didi

java - 如何从 Java servlet 运行外部命令?

转载 作者:塔克拉玛干 更新时间:2023-11-02 18:59:36 25 4
gpt4 key购买 nike

我正在开发一个小型 Web 应用程序,它请求用户输入并将该输入作为服务器端计算机上外部程序的命令行参数传递。

public class WorkflowServlet extends HttpServlet 

public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
String username = request.getParameter( "username" );
String workflow = request.getParameter( "workflow" );
String preInflation = request.getParamater( "preInflation" );
String email = request.getParamater( "email" );

try {
executeShellCommand( "java ClusterProcess " + username + " "
+ workflow + " " + preInflation + " " + email );
} catch ( Exception e ) {
response.sendRedirect( "WorkflowAction.jsp" ); return;
}

response.sendRedirect( "WorkflowInProgress.jsp" );
}
}


public static void executeShellCommand( String command ) {
Runtime.getRuntime().exec( command.split( " " ) ).waitFor();
}
}

没有抛出异常 - 它似乎什么都不做。即使我将一些非常简单的东西(例如“touch test.txt”)传递给 executeShellCommmand,它也不会执行任何操作。我可以通过命令行手动成功运行命令。

我必须做什么?

最佳答案

如果不捕获输入流或错误流,您就会错过来自流程的潜在反馈。我从我以前写的东西中改编了以下代码(在我的 IDE 之外),所以如果有明显的错误,我深表歉意。

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
...

String[] commands = {"/usr/bin/touch", "/home/blah/test.txt"};
//this could be set to a specific directory, if desired
File dir = null;
BufferedReader is = null;
BufferedReader es = null;

try
{
Process process;
if (dir != null)
process = Runtime.getRuntime().exec(commands, null, directory);
else
process = Runtime.getRuntime().exec(commands);
String line;
is = new BufferedReader(new InputStreamReader(process.getInputStream()));
while((line = is.readLine()) != null)
System.out.println(line);
es = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while((line = es.readLine()) != null)
System.err.println(line);

int exitCode = process.waitFor();
if (exitCode == 0)
System.out.println("It worked");
else
System.out.println("Something bad happend. Exit code: " + exitCode);
} //try
catch(Exception e)
{
System.out.println("Something when wrong: " + e.getMessage());
e.printStackTrace();
} //catch
finally
{
if (is != null)
try { is.close(); } catch (IOException e) {}
if (os != null)
try { es.close(); } catch (IOException e) {}
} //finally

关于java - 如何从 Java servlet 运行外部命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8736293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com