我正在尝试构建一个在我机器上的 tomcat 服务器中运行的简单 java servlet。
我的servlet代码是:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class javaservlet
*/
@WebServlet(description = "java servlet", urlPatterns = { "/javaservlet" })
public class javaservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public javaservlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter writer = response.getWriter();
calldll callingdll = new calldll();
ServletContext context = getServletConfig().getServletContext();
String path = context.getContextPath();
writer.println(path);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
它工作正常(不是calldll callingdll = new calldll();
我将在下面解释我遇到什么错误的部分)
我还有一个加载名为“calldll.dll”的dll文件的第二个类(使用javac,javah和其他东西完成了所有工作并且它工作)我的dll被放置在C:\apache-tomcat-7.0.37\wtpwebapps\myServlet\WEB-INF\lib
我已经指出了本地的构建路径和我的类代码是
public class calldll {
private native void print();
public static void main (String[] args){
new calldll().print();
}
static {
System.loadLibrary("calldll");
}
}
我从中制作 dll 的 c 文件非常简单
#include<jni.h>
#include<stdio.h>
#include<windows.h>
#include "calldll.h"
JNIEXPORT void JNICALL
Java_calldll_print(JNIEnv*env,jobject obj)
{
printf("It Works!");
return;
}
当我运行 javaservlet 时,我调用加载 dll 的调用 dll 类,我得到这个:
java.lang.NoClassDefFoundError: Could not initialize class calldll
javaservlet.doGet(javaservlet.java:33)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
奇怪的是,当我单独运行 java 类时,出现“它可以工作”的消息,因此该类成功加载了 dll。但是,当我在 servlet 中创建类的实例时,它不是来自 servlet 的,这不是我的问题....
我添加到 calldll 类
catch(UnsatisfiedLinkError e) { System.err.println("本地代码库加载失败。\n" + e); }
看看它是否是静态问题,当我运行 servlet 时出现以下错误
Native code library failed to load.
java.lang.UnsatisfiedLinkError: no calldll in java.library.path
但是我的 calldll 类如果我单独执行它仍然可以工作......所以在 servlet 中发生了什么我做错了:s