3

Lately I have been looking into having a servlet with a local database. With a bit of research I found H2 Database Engine (Wikipedia). This is perfect for what I want but I am having trouble with the local path for my servlet.

Example:

I need to create the H2 Database in my WebContent folder so its apart of the project. However I cannot seem to get the code right to localise it.

Example CODE: - H2.Jar - Connection String to SQL Database

             String url = "jdbc:h2:"+request.getContextPath()+"/emailDB;IFEXISTS=TRUE";
         Class.forName("org.h2.Driver");
            Connection conn = DriverManager.
                getConnection(url, "adminuser", "pass");

Example CODE (ERROR): - H2.Jar - Connection String to SQL Database (OUTPUT)

org.h2.jdbc.JdbcSQLException: Database "C:/emailservlet/emailDB" not found [90013-174]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:332)
at org.h2.message.DbException.get(DbException.java:172)
at org.h2.message.DbException.get(DbException.java:149)
at org.h2.engine.Engine.openSession(Engine.java:54)
at org.h2.engine.Engine.openSession(Engine.java:160)
at org.h2.engine.Engine.createSessionAndValidate(Engine.java:139)
at org.h2.engine.Engine.createSession(Engine.java:122)
at org.h2.engine.Engine.createSession(Engine.java:28)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:323)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:105)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:90)
at org.h2.Driver.connect(Driver.java:73)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at emailservlet.msdbcon(emailservlet.java:540)

As you can see the issue i am getting is that even though im requesting the contextpath i am still getting C:/ written before.

If you can help me figure out the error in my code that would be so helpful!

Thank you in advance!

4

1 回答 1

3

驱动程序需要它可以创建文件的文件系统路径。它使用 C: 驱动器的根目录将相对路径转换为绝对路径。要获取 WebContent 文件夹的绝对路径,您需要使用ServletContext#getRealPath()

此外,将 H2 文件存储在 WebContent 文件夹中也不是一个好主意,您应该将它们存储在 WEB-INF 文件夹中,以便用户无法访问它。

下面是应该如何形成 url

String path = getServletContext().getRealPath("/") + "/WEB-INF";
String url = "jdbc:h2:"+path+"/emailDB;IFEXISTS=TRUE";

这将在 WEB-INF 文件夹中创建 H2 文件。

取自H2Database.com 网站上的功能页面的注意事项:

  • 用于连接到本地数据库的数据库 URL 是 jdbc:h2:[file:][] 。前缀文件:是可选的。如果不使用或仅使用相对路径,则使用当前工作目录作为起点
  • 路径和数据库名称是否区分大小写取决于操作系统,但建议仅使用小写字母。
  • 数据库名称的长度必须至少为三个字符(File.createTempFile 的限制)。
  • 数据库名称不能包含分号。
  • 要指向用户主目录,请使用 ~/,如:jdbc:h2:~/test。
于 2013-11-05T10:58:10.813 回答