如何以编程方式知道服务器是否正在运行?

时间:2013-04-06 10:32:39

标签: java servlets jboss

我刚刚与本地主机建立了一个url连接: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");}
    }}

如果HTTP响应代码超出200-209或无法建立连接,则必须执行以下步骤:

1)如果Jboss服务正在运行,请重新启动。

2)如果Jboss服务未运行,则启动它。

现在我想知道如何以编程方式知道服务器是否正在运行以执行上述两个步骤..请帮助我...谢谢你

2 个答案:

答案 0 :(得分: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");}
    }}

答案 1 :(得分:1)

我认为这已经讨论过了。你需要捕获异常。您可能希望查看this

之类的内容