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

时间:2012-01-05 00:57:35

标签: java servlets runtime.exec

我正在开发一个请求用户输入的小型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”来执行ShellCommmand,它也什么也没做。我可以通过命令行手动成功运行命令。

我该怎么办?

2 个答案:

答案 0 :(得分:2)

通过不捕获输入流或错误流,您将缺少来自该过程的潜在反馈。我从之前编写过的内容中修改了以下代码(在我的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

答案 1 :(得分:1)

你让exec()混淆了某些东西并使用了一个包含各种漂亮东西的shell ......就像搜索路径一样。

指定您想要exec()的流程的完整路径;例如/usr/bin/touch/path/to/java