2008-11-22 29 views
2

我有一個簡單的Web應用程序,有幾個JSP頁面,servlet和POJO的。我想在做任何請求之前初始化連接池。做這個的最好方式是什麼?可以在應用程序首次部署時完成,還是必須等到第一次請求進入?正在初始化Java的Web應用程序

+0

請不要跟我重新標記被打亂。雖然你和我(以及其他人)知道它真的是拼寫成'初始化',但接受的標籤是'初始化'。 – MPelletier 2010-04-12 17:42:13

回答

0

怎麼樣一個基本的servlet啓動初始化連接池?

8

使用一個的ServletContextListener並在web.xml中正常申報。這種方式比啓動servlet更可取。它更有組織,你的意圖是顯而易見的。它也保證在任何請求之前運行。它還爲您提供關閉掛鉤以清除池。

這裏是我的web.xml片段,例如:

<listener> 
    <listener-class> 
    com...ApplicationListener 
    </listener-class> 
</listener> 

,這裏是從類本身的代碼片段。請確保你趕上例外,所以他們不會傳播到你的服務器應用程序,並提供有用的日誌消息 - 這些將幫助您,當您跟蹤您的應用程序。

public class ApplicationListener implements ServletContextListener { 

    private ServletContext sc = null; 

    private Logger log = Logger 
    .getLogger(ApplicationListener.class); 

    public void contextInitialized(ServletContextEvent arg0) { 
    this.sc = arg0.getServletContext(); 
    try { 
     // initialization code 
    } catch (Exception e) { 
     log.error("oops", e); 
    } 
    log.info("webapp started"); 
    } 

    public void contextDestroyed(ServletContextEvent arg0) { 
    try { 
     // shutdown code 
    } catch (Exception e) { 
     log.error("oops", e); 
    } 
    this.sc = null; 
    log.info("webapp stopped"); 
    } 

} 

請參閱API here和實例here

+0

你認爲「哎呀」是一個有用的信息? :-) – extraneon 2010-04-12 14:18:57