Search code examples
javaspringtomcathsqldb

Relative path to hsqldb files in a web app doesn't work?


I'm using hsqldb for my Spring-based java webapp. I put database files (mydb.lck, mydb.properties,..) in src\main\java\data folder so that they're published into WEB-INF\classes\data.

In datasource configuration, I specify this relative path to JVM working directory. As guided in hsqldb documents.

portal.jdbc.url=jdbc:hsqldb:file:/data/mydb (Is this seperator right for Windows?)

But Spring seem not find this path and insist on claiming

java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: CUSTOMER org.hsqldb.jdbc.Util.sqlException(Unknown Source)

However, if I specify an absolute path, it works flawlessly

portal.jdbc.url=jdbc:hsqldb:file:d:\\TomcatServer\\apache-tomcat-7.0.10\\wtpwebapps\\myportal-app\\data\\mydb

Should I miss understanding JVM working directory on a web app? Any help is appreciated.


Solution

  • It seems that Tomcat doesn't provide us a properties variable (like "webroot") to refer to my application context. So my solutions is to register such a properties in Servlet context listener.

    My code:

     public class WebAppPropertiesListener implements ServletContextListener{
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            String rootPath = sce.getServletContext().getRealPath("/");
            System.setProperty("webroot", rootPath);
    
        }
        ...
     }
    

    And add listener in web.xml before Spring context is triggered

    <listener>
        <listener-class>com.iportal.util.WebAppPropertiesListener</listener-class>
    </listener>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    

    Then I put the property in Hsqldb setting.

    portal.jdbc.url=jdbc:hsqldb:file:${webroot}WEB-INF/classes/data/mydb
    

    Hope this helpful for someone who may run into the same problem.