java中Web Project中載入dll檔案的終極解決方案

來源:互聯網
上載者:User

1.首先把要載入的dll檔案拷貝到Web Project的src目錄下

2.聲明一個TestDLL類,名字請根據實際命名

 代碼如下 複製代碼

package com.anllin.jni;

public class TestDLL
{
    public TestDLL(String... filenames)
    {
        // 取得src下的實體路徑,
        String path = TestDLL.class.getResource("/").getPath();
        // 將路徑裡的%20替換成空格,不然在src目錄下會找不到dll檔案
        path = path.replaceAll("%20", " ");
        //output : /D:/myEclispe8.6 projects/jnitest/WebRoot/WEB-INF/classes/
        System.out.println(path);
        //註:使用System.load()時,檔案名稱必須包含.dll尾碼,如test1.dll
        for (String filename : filenames)
        {
            System.load(path + filename);
        }
    }

    public native void test1();

    public native void test2();

    public native void test3();
}

 

3.聲明一個調用類TestInvoker,名字請根據實際命名

 代碼如下 複製代碼

package com.anllin.jni;

public class TestInvoker
{
    private TestDLL testDll;

    public TestInvoker()
    {
        // 注意,一定要確定DLL之間的依賴關係,誰先載入,誰後載入,不然會報錯,先載入的放在前面
      testDll = new TestDLL("test1.dll", "test2.dll", "test3.dll");
    }

    public void test1()
    {
        testDll.test1();
    }

    public void test2()
    {
        testDll.test2();
    }

    public void test3()
    {
        testDll.test3();
    }
}

4.這種Dll檔案載入方式的好處:

a.當你有多個Web Project,每個都要去調用DLL時,就不衝突了,如果DLL是放在tomcat的bin下的話,每載入一次都是載入相同的dll,會報錯,我做的項目就是這樣。

b.DLL檔案好管理,放到src下就行,就算多個Web Project,每一份DLL都是一個拷貝,彼此之間不依賴,耦合性低。

c.方便布署,將項目打包成war包後,就象一般項目一樣,放到tomcat裡就行了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.