1. First copy the dll file to be loaded to the src Directory of the Web Project.
2. Declare a TestDLL class. Name it based on the actual name.
The code is as follows: |
Copy code |
Package com. anllin. jni; Public class TestDLL { Public TestDLL (String... filenames) { // Obtain the physical path under src, String path = TestDLL. class. getResource ("/"). getPath (); // Replace % 20 in the path with a space. Otherwise, the dll file cannot be found in the src directory. Path = path. replaceAll ("% 20 ",""); // Output:/D:/myEclispe8.6 projects/jnitest/WebRoot/WEB-INF/classes/ System. out. println (path ); // Note: When System. load () is used, the file name must contain the. dll suffix, for example, test1.dll. For (String filename: filenames) { System. load (path + filename ); } } Public native void test1 (); Public native void test2 (); Public native void test3 (); } |
3. Declare a call class TestInvoker. The name must be based on the actual name.
The code is as follows: |
Copy code |
Package com. anllin. jni; Public class TestInvoker { Private TestDLL testDll; Public TestInvoker () { // Note that you must determine the dependencies between the DLL, who loads the DLL first, and who loads the DLL later. Otherwise, an error will be reported. Load the DLL first. 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. Advantages of this Dll file loading method:
A. when you have multiple Web projects and each has to call the DLL, there is no conflict. If the DLL is placed in the bin of tomcat, the same dll is loaded every time, an error is reported. This is the case for my project.
B. The DLL file is well managed and put under src. Even if multiple Web projects are used, each DLL is a copy, independent of each other, and the coupling is low.
C. Facilitate deployment. After packaging the project into a war package, just like a normal project, put it in tomcat.