代码之家  ›  专栏  ›  技术社区  ›  Geo

为我的servlet配置sqlite数据库路径的正确方法是什么?

  •  1
  • Geo  · 技术社区  · 15 年前

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

    文件夹 db 位于正下方 WebContent ,所以,要访问它,我需要使用 ServletContext getRealPath 方法。为了使用它,我需要访问一个servlet,因为我不确定哪个servlet将是第一个被调用的servlet,所以我需要在我的所有请求中执行一个检查,看看数据库是否已经设置好,如果还没有设置好。我想应该有更好的办法。 目前,我创建了一个从HttpServlet继承的抽象类,添加了两个方法,一个 getImpl postImpl (都是摘要)和我的 doGet doPost

        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 回复  |  直到 15 年前
        1
  •  2
  •   BalusC    15 年前

    您想使用 ServletContextListener 挂接webapp的启动并初始化应用程序范围的参数。下面是一个启动示例,假设您确实已将路径定义为 <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>
    

    如果需要,可以将上下文范围的变量存储在 ServletContext 因此,任何servlet都可以依次访问它。

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

    ...

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

    < 获取/初始化 DataSource (间接地)在 往那边走。

    更多的提示你可能会发现 this basic example 有用。

        2
  •  2
  •   Pascal Thivent    15 年前

    正确的方法是在服务器级别配置连接池,并在代码中使用数据源(注入或通过JNDI获得)从数据源获取连接。