2012-07-05 62 views

回答

1

執行javax.servlet.SevletContextListenerjavax.servlet.ServletContext被初始化時會得到一個回調。

這裏是例子:

public class MyServletContextListener implements ServletContextListener 
{ 
    public void contextInitialized(ServletContextEvent sce) 
    { 
     ServletContext sc = sce.getServletContext(); 
     //do your initialization here. 
     sc.setAttribute(.....); 
    } 

    public void contextDestroyed(ServletContextEvent sce) 
    { 
     ServletContext sc = sce.getServletContext(); 
     //do your cleanup here 

    } 
} 
+0

太棒了!正是我想要的.thx – Lopakhin

+1

不應該使用'@ WebListener'來註銷'MyServletContextListener'嗎?請參閱[文檔](http://docs.oracle.com/javaee/6/api/javax/servlet/annotation/WebListener.html)。 –

+0

當然你必須在某個地方定義你的Listener。通過1)Annoatation 2)在web.xml或3)在TLD中。 –

1

如果你想以配合你的邏輯更接近的servlet(而不是使用偵聽器),你可以重寫的servlet init方法。像這樣:

@Override 
public void init() throws ServletException { 
    ServletContext sc = getServletContext(); 

    // Store our attribute(s)! 
    // Check first to make sure it hasn't already been set by another Servlet instance. 
    if (sc.getAttribute("key") == null) 
     sc.setAttribute("key", "value"); 
} 

而且你不必通過打電話super.init(config)。見docs