Eclipse Juno EE NoClassDefFoundError when using ex

2019-09-13 02:30发布

问题:

I added an external jar in my eclipse dynamic webproject via Folder -> properties -> build path -> Libraries -> add external jar.

The code is working fine on compile time.

package servlet;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tika.Tika;

@WebServlet(name="UploadServlet", urlPatterns={"/uploadFile"})     // specify urlPattern for servlet
@MultipartConfig                       //Specify that this servlet will receive a multipart data
public class UploadServlet extends HttpServlet {

    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{
        Tika tika = new Tika();

        res.setContentType("text/html");
        PrintWriter writer = res.getWriter();
        writer.write(mediaType);
    }
}

I added Apache Tika but when I run my application. these exception occured.

root cause 

java.lang.NoClassDefFoundError: org/apache/tika/Tika
    servlet.UploadServlet.doPost(UploadServlet.java:19)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)


root cause 

java.lang.ClassNotFoundException: org.apache.tika.Tika
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
    servlet.UploadServlet.doPost(UploadServlet.java:19)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

I am using Apache Tika to determine what file has been upload, I want to use it for validating if a file is an image, or audio file

回答1:

You forgot to add that jar to the Deployment Assembly page. It's not deployed to the server when you run your application, hence the NoClassDefFoundErrors.