2013-04-06 76 views
1

我剛剛建立了一個到本地主機的連接:8080,並使用JBOSS服務器檢查了200-209之間的http響應代碼。如何以編程方式知道服務器是否在運行?

public class Welcome extends HttpServlet { 

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

response.setContentType("text/html"); 
PrintWriter pw = response.getWriter(); 
URL url = new URL("http://localhost:8080"); 
HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
connection.setRequestMethod("GET"); 
connection.connect(); 

int code = connection.getResponseCode(); 
System.out.println("code=="+code); 
if (code>=200 && code <= 209){ 

     pw.println("<h1>Welcome....</h1>"); 
     pw.println("<p>Service is accessable</p>"); 


    } 
else 

{System.out.println("service is denied");} 
    }} 

如果200-209或無法使連接外部的HTTP響應代碼,那麼它必須執行以下步驟:

1)如果JBoss的服務正在運行,然後重新啓動。

2)如果Jboss服務沒有運行,然後啓動它。

現在,這裏我想知道如何通過編程知道服務器是否是爲了執行上述2步運行或不..請幫助那些起來時超時me..Thanks你

回答

2

你應該趕上IOException異常(服務器根本沒有運行)。

事情是這樣的:

public class Welcome extends HttpServlet { 

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

response.setContentType("text/html"); 
PrintWriter pw = response.getWriter(); 
URL url = new URL("http://localhost:8080"); 

try { 
    HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
} catch (IOException ex) { 
    // (probably) service is not running 
    // start service 
    return; 
} 

connection.setRequestMethod("GET"); 
connection.connect(); 

int code = connection.getResponseCode(); 
System.out.println("code=="+code); 
if (code>=200 && code <= 209){ 

     pw.println("<h1>Welcome....</h1>"); 
     pw.println("<p>Service is accessable</p>"); 


    } 
else 

{System.out.println("service is denied");} 
    }} 
+0

謝謝..但我不明白這一點...可以請簡要介紹一下這個步驟:如果HTTP響應代碼200-209之外,那麼它必須執行步驟如下:1)如果Jboss服務正在運行,則重新啓動。 2)如果Jboss服務沒有運行,那麼啓動它 – user2249134 2013-04-06 11:11:46

+0

看我的編輯.... – PeterMmm 2013-04-06 16:02:55

1

我認爲這是已經討論過的東西。你需要捕捉異常。你可能想看看像this

+0

請你看看這個:如果HTTP響應代碼200-209之外或無法建立連接,那麼它必須執行步驟如下: 1)如果Jboss服務正在運行,則重新啓動。 2)如果Jboss服務沒有運行,然後啓動它。 – user2249134 2013-04-06 11:08:50

相關問題