我正在使用tomcat作为容器运行应用程序 - 在启动时,需要找到并加载几个文件。但是,如果其中一个文件不存在或无法读取,我想记录异常并退出应用程序,我目前正在使用System.exit(1)...但是,有没有更好的这样做的方式?
非常感谢任何帮助!
答案 0 :(得分:3)
我不知道这是否符合您的需求,但它实际上适用于我的应用程序。听众是 在应用程序启动时调用,如果它在web.xml中声明:
<listener>
<listener-class>your.package.TestServletListener</listener-class>
</listener>
如果一个失败,你可以进行测试并调用ShutdownThread。它将连接到Tomcats关闭端口并以字符串形式发送shutdown命令:
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 port和shutdown命令与Tomcats server.xml同步:
...
<Server port="8015" shutdown="shutdown">
...
例如,您可以将它们作为web.xml中的上下文参数传递。与System.exit(...)一样,如果Tomcat与SecurityManager一起运行,这将无法工作(没有进一步的配置)。
答案 1 :(得分: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.");
}
}
}
您可以在Internet上找到如何嵌入Tomcat教程。