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

时间:2010-06-08 16:40:05

标签: java servlets initialization

我正在使用SQLite作为我的数据库,我对如何配置它的路径感到有些困惑。基本上,我的一个类中有一个静态字符串(在初始化之后转为类似的东西):

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

文件夹db位于WebContent的正下方,因此,要访问它,我需要使用ServletContext的{​​{1}}方法。要使用它,我需要访问一个servlet,因为我不确定哪个servlet将是第一个被调用的,我需要检查所有请求以查看数据库是否已设置,并且如果还没有设置它。我认为应该有更好的方法来做到这一点。 目前,我创建了一个继承自HttpServlet的抽象类,添加了两个方法,一个getRealPath和一个getImpl(都是抽象的),我的postImpldoGet是目前实施如下:

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

我现在做事的方式感觉不对。当然必须有更好的方法。

2 个答案:

答案 0 :(得分:2)

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

如果您添加有关服务器的更多详细信息,我可以提供更多指导。

答案 1 :(得分:2)

您希望使用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");

正如帕斯卡尔在答案中暗示的那样,你想在每个JNDI下使用它。在这种情况下,您可以将JNDI名称存储为<context-param>,并以ServletContextListener的方式获取/初始化DataSource(间接)。

有关更多提示,您可能会发现this basic example有用。