我正在尝试构建一个在我机器上的 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
并且我已经指出了 native 的构建路径,我的类代码是
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 类时,会出现“It works”消息,因此该类成功加载了 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
最佳答案
如果您的 webapp 托管在 tomcat 应用服务器中,将 dll 复制到 bin 文件夹,然后在您的 servlet 中使用:
System.load(System.getProperty("catalina.base")+"/bin/yourdll.dll");
关于java - 尝试使用tomcat在servlet中加载dll时出现NoClassDefFoundError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15108672/