2012-01-05 43 views
3

我正在開發一個小型web應用程序,它要求用戶輸入並將該輸入作爲服務器端計算機上外部程序的命令行參數傳遞。如何從Java servlet運行外部命令?

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」來執行executeShellCommand,它也不會執行任何操作。我可以通過命令行手動成功運行該命令。

我該做什麼?

+0

爲什麼「分裂」? – davogotland 2012-01-05 01:04:22

+0

另外,爲什麼你不使用waitFor的返回值?它可能會告訴你一些事情。 – davogotland 2012-01-05 01:08:26

+0

你可以發佈它正在運行的URL嗎? (沒有,請勿 - 您不會逃避用戶輸入!!) – 2012-01-05 01:14:54

回答

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 
+0

您的代碼不能解決該問題。該servlet不能正確重定向。 – artaxerxe 2012-11-21 12:38:16

+2

@artaxerxe - 我不確定你的意思。原始文章中沒有關於重定向的內容。另外,我提供的代碼示例是演示如何讀取輸入流和錯誤流。它並不打算成爲一個servlet的例子。 – 2012-11-26 19:37:32

1

你很困惑exec()一些東西,並使用一個具有各種漂亮事情的外殼...像一個搜索路徑。

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