编程语言
首页 > 编程语言> > 如何从Java servlet运行外部命令?

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

作者:互联网

我正在开发一个小型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

标签:runtime-exec,servlets,java
来源: https://codeday.me/bug/20191201/2084360.html