2010-06-08 23 views
1

我正在使用SQLite作爲我的數據庫,我對如何配置它的路徑有點困惑。基本上,我有一個靜態的字符串在我的課(其中,初始化變成這樣的事情之後)之一:什麼是正確的方式來配置我的servlets使用的sqlite數據庫的路徑?

private static String DATABASE = "db/my.db"; 

文件夾db直接位於WebContent下,所以,去訪問它,我需要使用ServletContextgetRealPath方法。爲了使用它,我需要訪問一個servlet,並且由於我不確定哪個servlet將成爲第一個被調用的servlet,因此我需要對所有請求進行檢查,以查看數據庫是否已設置,以及如果它沒有設置它。我認爲應該有更好的方法來做到這一點。 就目前而言,我創建了一個抽象類,繼承自HttpServlet,增加了2種方法,一個getImplpostImpl(既抽象),和我的doGetdoPost目前這樣實現的:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     App.checkDatabase(this); 
     try { 
      getImpl(request,response); 
     } catch(Exception e) { 
      throw new RuntimeException(e); 
     } 
    } 

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     App.checkDatabase(this); 
     try { 
      postImpl(request,response); 
     } catch(Exception e) { 
      throw new RuntimeException(e); 
     } 

而且我checkDatabase方法是這樣實現的:

public static void checkDatabase(HttpServlet servlet) 
{ 
    if(App.DATABASE == null) { 
     App.DATABASE = "jdbc:sqlite:"+servlet.getServletContext().getRealPath(
      servlet.getServletContext().getInitParameter("DATABASE") 
     ); 
    } 
} 

我現在做事情的方式感覺不對。當然,一定有更好的辦法。

回答

2

您想使用ServletContextListener鉤住webapp的啓動並初始化應用程序範圍的參數。這裏有一個開球例如假設你確實definied路徑爲<context-param><context-name>DATABASE的:

public class Config implements ServletContextListener { 

    public void contextInitialized(ServletContextEvent event) { 
     String database = event.getServletContext().getInitParameter("DATABASE"); 
     // ... 
    } 

    // ... 

} 

然後您可以在web.xml圖如下:

<listener> 
    <listener-class>com.example.Config</listener-class> 
</listener> 

如有必要,可以儲存contextwide變量在ServletContext中,這樣任何servlet都可以訪問它。

event.getServletContext().setAttribute("database", database); 

...

Database database = (Database) getServletContext().getAttribute("database"); 

帕斯卡在他的回答暗示,你想每一個JNDI此下使用。在這種情況下,您可以將JNDI名稱存儲爲<context-param>,並以ServletContextListener(間接)方式獲取/初始化DataSource

有關更多提示,您可能會發現this basic example有用。

+0

謝謝!這比我做這件事的方式要好得多。 – Geo 2010-06-08 17:10:36

2

正確的方法是在服務器級配置連接池,並在代碼中使用數據源(通過注入或通過JNDI獲取)來獲取數據源的連接。

如果您添加更多有關您服務器的詳細信息,我可以提供更多指導。

+0

我正在使用Tomcat 6.14,並將其用作Web開發人員的Eclipse Eclipse EE IDE。 – Geo 2010-06-08 16:52:40

+0

@Geo沒關係:) – 2010-06-08 17:14:12

相關問題