2013-10-10 31 views
2

我正在運行一個使用tomcat作爲容器的應用程序 - 在啓動時,需要找到並加載幾個文件。但是,如果其中一個文件不存在或無法讀取,我想記錄該異常並退出該應用程序,目前我正在使用System.exit(1)...但是,是否還有更好的這樣做的方式?關閉使用Java的Tomcat實例

任何幫助非常感謝!

+0

一個簡單的解決方案是修改Tomcat的啓動腳本來檢查文件... – maksimov

+0

如果這些文件是特定於應用程序,那麼我不認爲它真的建議操縱tomcat的啓動腳本? – rvini

回答

3

我不知道這是否符合您的需求,但它實際上是爲我的應用程序工作。偵聽器 叫在應用程序啓動,如果在你的web.xml聲明:

<listener> 
    <listener-class>your.package.TestServletListener</listener-class> 
</listener> 

在那裏,你可以做測試,並調用ShutdownThread如果失敗。它將連接到雄貓關閉端口和一個String發送關機命令:

public class TestServletListener implements ServletContextListener { 

@Override 
public void contextInitialized(ServletContextEvent arg0) { 
    System.out.println("Starting app, running 5 tests ..."); 

    // do tests ... 
    for (int i = 0; i < 5; i++) { 
     System.out.println("testing ... " + i); 
     waitFor(1000); 
    } 
    // If a test failed call: 
    System.out.println("test failed!"); 
    new ShutdownTask().start(); 
} 

@Override 
public void contextDestroyed(ServletContextEvent arg0) { 
    System.out.print("Stopping app, cleaning up (takes 3 sec) ... "); 
    waitFor(3000); 
    System.out.println("done"); 
} 

private void waitFor(int i) { 
    try { 
     Thread.sleep(i); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
} 

class ShutdownTask extends Thread { 

    @Override 
    public void run() { 
     try { 
      Socket s = new Socket("127.0.0.1", 8015); 
      PrintStream os = new PrintStream(s.getOutputStream()); 
      os.println("shutdown"); 
      s.close(); 
      System.out.println("Shutting down server ..."); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
} 

你需要確保的是,關閉端口和shutdown命令是同步你的雄貓的server.xml:

... 
<Server port="8015" shutdown="shutdown"> 
... 

例如,您可以將它們作爲上下文參數傳遞到您的web.xml中。像System.exit(...),如果Tomcat與SecurityManager一起運行,這不會起作用(沒有進一步的配置)。

+0

是的,這似乎是我可以使用的東西 - 不知道聽衆可以這樣使用,謝謝! – KingTravisG

1

你應該考慮嵌入的Tomcat,即有你AppStarter類執行這些檢查,然後啓動Tomcat:

public class AppStarter { 
    public static void main(String[] args) { 
     // Check if everything is ready... 
     if (file1.exists() && file2.exists() && condition3) { 
      // Start Tomcat here. 
     } 
     else { 
      System.out.println("Invalid configuration."); 
     } 
    } 
} 

你可以找到如何嵌入在互聯網上的Tomcat教程。

+0

不幸的是,我不能在應用程序中嵌入tomcat ..我猜測System.exit()可能是唯一的方法(除了在系統調用中調用kill -15應用程序) – KingTravisG

+0

你可以拋出在你的servlet的構造函數中異常,從而阻止應用程序啓動,但Tomcat仍將運行。除了'System.exit()'我沒有看到任何其他的方式。 – Cebence

+0

我在命令行中用'catalina stop'停止tomcat。如果路徑設置正確,它會有幫助嗎? – Piro