如何使用 Spring 将 HSQLDB 嵌入到 Web 应用程序的文件中

2024-05-19

我有一个带有Spring的web应用程序,当我在服务器模式下使用HSQLDB时它可以正常工作,但在文件模式下,它只通过了单元测试。这是我的数据源:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="driverClassName" value="org.hsqldb.jdbcDriver" />

     <property name="url" value="jdbc:hsqldb:hsql://localhost/images" />
    <property name="username" value="sa" />
    <property name="password" value="" />
</bean>

我只是改变这一行

   <property name="url" value="jdbc:hsqldb:hsql://localhost/images" />    
   ( -- Server mode)

for this

     <property name="url" value="jdbc:hsqldb:file:data/images" />      
     (-- In file)

它只是通过了单元测试,但在 Web 应用程序中失败了。

我想在文件模式下,当我运行web应用程序时,HSQLDB找不到数据库的文件。

我已经尝试将数据库的数据放在webapp的根目录和web-inf内,但它不起作用。


好吧,如果你将数据库放入 jar 中,如下所示:

<property name="url" value="jdbc:hsqldb:res:/data/images" />

您只能将其用作只读,如果您尝试插入或修改数据库将会失败。

一种解决方案是在 web.xml 中放置一个侦听器,这样当应用程序启动时,它将使用应用程序 Web 的根路径进行初始化。

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>maf</display-name>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>


     <!--This is to get root of the aplication-->

    <listener>
        <listener-class>
   org.atoms.HsqlDatabaseListener
        </listener-class>
    </listener>


       <!--Este listener se encarga de inicializar todo el contenedor de Spring y mantener una variable en el
  ServletContext que apunta a dicho contenedor -->

    <listener>
        <listener-class>
   org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>




</web-app>

听者:

package org.atoms;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;


/**
 *
 * @author atomsfat
 */
public class HsqlDatabaseListener implements ServletContextListener {

    private ServletContext context = null;

    public void contextInitialized(ServletContextEvent event) {
        context = event.getServletContext();

        String prefix = event.getServletContext().getRealPath("/");

        System.out.println("database root " + prefix);
        com.atoms.HsqlDatabasePathResolver.getInstance(prefix);


    }

    public void contextDestroyed(ServletContextEvent event) {
        context = event.getServletContext();

    }

另一类:

package com.atoms;


/**
 *
 * @author atomsfat
 */
public class HsqlDatabasePathResolver {


    private static HsqlDatabasePathResolver instance ;
    private static String applicationPath = "";

    private HsqlDatabasePathResolver() {
    }

      /** Get Instance.
   */
    static public synchronized HsqlDatabasePathResolver getInstance(String applicationPath) {

        if (instance == null) {

            HsqlDatabasePathResolver.applicationPath =
                    HsqlDatabasePathResolver.normalizePath(applicationPath);
            instance = new HsqlDatabasePathResolver();



            System.out.println("Inizalizando path : " + HsqlDatabasePathResolver.applicationPath);

        }
        return instance;
    }

    public  String getApplicationPath() {
        return applicationPath;
    }



      public  String getUrlDatabase(String urlDatabase) {


         return HsqlDatabasePathResolver.replaceAll(urlDatabase,"{apppath}", applicationPath);
    }


      /**

         *
         * replace the "\" character by "/" and remove relative paths
         *
         * @param path
         * @return
         */
        public static String normalizePath(String path) {
            if (path == null) {
                return null;
            }
            String normalized = path;
            if (normalized.equals("/.")) {
                return "/";
            }
            if (normalized.indexOf('\\') >= 0) {
                normalized = normalized.replace('\\', '/');
            }
            if (!normalized.startsWith("/") && normalized.indexOf(':') < 0) {
                normalized = "/" + normalized;
            }
            do {
                int index = normalized.indexOf("//");
                if (index < 0) {
                    break;
                }
                normalized = normalized.substring(0, index) + normalized.substring(index + 1);
            } while (true);
            do {
                int index = normalized.indexOf("/./");
                if (index < 0) {
                    break;
                }
                normalized = normalized.substring(0, index) + normalized.substring(index + 2);
            } while (true);
            do {
                int index = normalized.indexOf("/../");
                if (index >= 0) {
                    if (index == 0) {
                        return null;
                    }
                    int index2 = normalized.lastIndexOf('/', index - 1);
                    normalized = normalized.substring(0, index2) + normalized.substring(index + 3);
                } else {
                    return normalized;
                }
            } while (true);
        }




        public static String replaceAll(String str, String match, String replace) {
            if (match == null || match.length() == 0) {
                return str;
            }
            if (replace == null) {
                replace = "";
            }
            if(match.equals(replace))return str;
            StringBuffer ret=new StringBuffer();
            int i = str.indexOf(match);
            int y = 0;
            while (i >= 0)
            {
                //System.out.println("i:"+i+" y:"+y);
                ret.append(str.substring(y, i));
                ret.append(replace);
                //str = str.substring(y, i) + replace + str.substring(i + match.length());
                y = i + match.length();
                i = str.indexOf(match,y);
            }
            ret.append(str.substring(y));
            return ret.toString();
        }



}

这是我在 spring 中使用的配置:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
     xmlns:jee="http://www.springframework.org/schema/jee"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-2.5.xsd
               http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">

     <!-- La definición del Datasource -->
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" lazy-init="true"
      destroy-method="close">
            <property name="driverClassName" value="org.hsqldb.jdbcDriver" />

          <property name="url">
               <ref bean="dataBaseUrl"/>
           </property>

            <property name="username" value="sa" />
            <property name="password" value="" />
        </bean>

     <!-- La definición del Factory de Session con Anotaciones -->
        <bean id="sessionFactory"
      class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" lazy-init="false">
            <property name="dataSource" ref="dataSource" />
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">
         org.hibernate.dialect.HSQLDialect
                    </prop>
                    <prop key="hibernate.show_sql">true</prop>
                    <prop key="hibernate.format_sql">true</prop>
                </props>
            </property>
            <property name="mappingResources">
                <list>
                    <value>Atoms.hbm.xml</value>
                </list>

            </property>
        </bean>
     <!--HibernaTemplate-->
        <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
            <property name="sessionFactory">
                <ref bean="sessionFactory" />
            </property>
        </bean>
     <!-- Definición de los DAO`s -->

        <bean id="ipBlancaDao" class="org.atoms.impl.AtomsDaoHibernateImpl">
            <property name="hibernateTemplate" ref="hibernateTemplate" />
        </bean>


        <!--If your are not running in Web this will initialize with the directory from    the  process was started note that this classes is a singleton so if you are running in web the listener already have initialize the class with the path of the class-->


        <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"/>


     <bean id="hsqlDatabasePathResolver" class="com.atoms.HsqlDatabasePathResolver" factory-method="getInstance" lazy-init="false">
            <constructor-arg>
                <value>${user.dir}</value>
            </constructor-arg>
        </bean>

   <!--This bean just replace {apppath} whit the absolute path-->

        <bean id="dataBaseUrl" class="java.lang.String" factory-bean="hsqlDatabasePathResolver" lazy-init="false"
                      factory-method="getUrlDatabase">
            <constructor-arg>
                <value>jdbc:hsqldb:mem:{apppath}/WEB-INF/data/maf</value>
            </constructor-arg>

        </bean>  
    </beans>

是的,这个工作很混乱,我认为解决方案是监听器,用它你可以获取appWeb的路径。如果有人可以使这个简单,请发布答案。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Spring 将 HSQLDB 嵌入到 Web 应用程序的文件中 的相关文章

  • 如何创建一个显示 Spinners 的 x 和 y 值的表格?

    我想创建一个位于图表右侧的表格 其中显示 2 列 x 和 y 值已输入到xSpin and ySpin旋转器 我已经画了一张我想要桌子放置的位置的图 我尝试过在网格窗格布局中使用文本框来创建表格并将值直接输入到文本框网格中 但是我无法将它们
  • 是什么决定了从 lambda 创建哪个函数式接口?

    请考虑这个例子 import java util function Consumer public class Example public static void main String args Example example new
  • SAML 服务提供商 Spring Security

    当使用预先配置的服务提供者元数据时 在 Spring Security 中 是否应该有 2 个用于扩展元数据委托的 bean 定义 一份用于 IDP 元数据 一份用于 SP 元数据
  • OpenCV 中的 Gabor 内核参数

    我必须在我的应用程序中使用 Gabor 过滤器 但我不知道这个 OpenCV 方法参数值 我想对虹膜进行编码 启动 Gabor 过滤器并获取特征 我想对 12 组 Gabor 参数值执行此操作 然后我想计算 Hamming Dystans
  • Android在排序列表时忽略大小写

    我有一个名为路径的列表 我目前正在使用以下代码对字符串进行排序 java util Collections sort path 这工作正常 它对我的 列表进行排序 但是它以不同的方式处理第一个字母的情况 即它用大写字母对列表进行排序 然后用
  • 在Spring中使用什么样的“EventBus”?内置、Reactor、Akka?

    我们将在几周后启动一个新的 Spring 4 应用程序 我们希望使用一些事件驱动的架构 今年 我到处读到有关 Reactor 的内容 在网上查找时 我偶然发现了 Akka 所以现在我们有3个选择 春天的ApplicationEvent ht
  • 当从服务类中调用时,Spring @Transactional 不适用于带注释的方法

    在下面的代码中 当方法内部 是从内部调用的方法外部 应该在交易范围内 但事实并非如此 但当方法内部 直接从调用我的控制器class 它受到事务的约束 有什么解释吗 这是控制器类 Controller public class MyContr
  • 我需要什么库才能在 Java 中访问这个 com.sun.image.codec.jpeg?

    我正在用java创建一个图像水印程序 并导入了以下内容 import com sun image codec jpeg JPEGCodec import com sun image codec jpeg JPEGEncodeParam im
  • 使用 AES SecretKey 的 Java KeyStore setEntry()

    我目前正在 Java 中开发一个密钥处理类 特别是使用 KeyStore 我正在尝试使用 AES 实例生成 SecretKey 然后使用 setEntry 方法将其放入 KeyStore 中 我已经包含了代码的相关部分 The KS Obj
  • 画透明圆,外面填充

    我有一个地图视图 我想在其上画一个圆圈以聚焦于给定区域 但我希望圆圈倒转 也就是说 圆的内部不是被填充 而是透明的 其他所有部分都被填充 请参阅这张图片了解我的意思 http i imgur com zxIMZ png 上半部分显示了我可以
  • Hazelcast 分布式锁与 iMap

    我们目前使用 Hazelcast 3 1 5 我有一个简单的分布式锁定机制 应该可以跨多个 JVM 节点提供线程安全性 代码非常简单 private static HazelcastInstance hInst getHazelcastIn
  • 以编程方式在java的resources/source文件夹中创建文件?

    我有两个资源文件夹 src 这是我的 java 文件 资源 这是我的资源文件 图像 properties 组织在文件夹 包 中 有没有办法以编程方式在该资源文件夹中添加另一个 properties 文件 我尝试过这样的事情 public s
  • 如何在selenium服务器上提供自定义功能?

    我知道可以通过某种方法获得一些硒功能 其中之一如下 driver getCapabilities getBrowserName 它返回浏览器名称的值 但如果它指的是一个可用的方法 如果我没有误解的话 这似乎与自定义功能有关 就像我的意思是
  • 有没有一种快速方法可以从 Jar/war 中删除文件,而无需提取 jar 并重新创建它?

    所以我需要从 jar war 文件中删除一个文件 我希望有类似 jar d myjar jar file I donot need txt 的内容 但现在我能看到从 Linux 命令行执行此操作的唯一方法 不使用 WinRAR Winzip
  • 我可以创建自定义 java.* 包吗?

    我可以创建一个与预定义包同名的自己的包吗在Java中 比如java lang 如果是这样 结果会怎样 这难道不能让我访问该包的受保护的成员 如果不是 是什么阻止我这样做 No java lang被禁止 安全管理器不允许 自定义 类java
  • 具有特定参数的 Spring AOP 切入点

    我需要创建一个我觉得很难描述的方面 所以让我指出一下想法 com x y 包 或任何子包 中的任何方法 一个方法参数是接口 javax portlet PortletRequest 的实现 该方法中可能有更多参数 它们可以是任何顺序 我需要
  • 如何使用 JSch 将多行命令输出存储到变量中

    所以 我有一段很好的代码 我很难理解 它允许我向我的服务器发送命令 并获得一行响应 该代码有效 但我想从服务器返回多行 主要类是 JSch jSch new JSch MyUserInfo ui new MyUserInfo String
  • hashcode 的默认实现为以相同方式构造的对象返回不同的值

    我在这里编写一个示例代码 public class Test private int i private int j public Test TODO Auto generated constructor stub public Test
  • Trie 数据结构 - Java [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 是否有任何库或文档 链接提供了在 java 中实现 Trie 数据结构的更多信息 任何帮助都会很棒 Thanks 你可以阅读Java特里树
  • 在 RESTful Web 服务中实现注销

    我正在开发一个需要注销服务的移动应用程序 登录服务是通过数据库验证来完成的 现在我陷入了注销状态 退一步 您没有提供有关如何在应用程序中执行身份验证的详细信息 并且很难猜测您在做什么 但是 需要注意的是 在 REST 应用程序中 不能有会话

随机推荐