ServletContextListener 可以監聽servlet 生命周期
項目啟動的時候應該會執行 其
contextInitialized() 才對
但是樓主的並沒有執行,到底是為什麼?
代碼如下:
public class init implements ServletContextListener{
private ExecutorService threadService;
private Timer timer;
public init()
{
threadService = Executors.newFixedThreadPool(1);
timer = new Timer();
}
public void contextInitialized(ServletContextEvent arg0) {
InputStream in = init.class.getResourceAsStream("/config.properties");
Properties p = new Properties();
try {
p.load(in);
Constant.Config = (Hashtable) p.clone();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TimerTask accessTask = new AccessToken();
TimerTask initMenu = new InitMenu();
}
是這樣的沒錯啊,關鍵是你有沒有在web.xml中的listener節點下配置這個ServletContextListener的監聽器呢?
配置實例代碼:
<listener>
<listener-class>
com.listeners.MyContextListener
</listener-class>
</listener>
<servlet/>
<servlet-mapping/>