我正在尝试在tomcat 7中运行一个servlet fileupload示例,该示例基于org.apache.commons.fileupload
我使用此命令在CMD(Win 7 64位)中编译了servlet类文件。
C:\Users\Preet\Desktop>javac -cp .;E:/servlet-api.jar;"C:\Program Files\Apache S
oftware Foundation\Tomcat 7.0\webapps\sim\WEB-INF\lib\commons-fileupload-1.2.2.j
ar" "C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\sim\WEB-INF\
classes\SimpleServlets.java"
一切都很好。
编译后,我尝试了我的例子,我得到了一个错误
exception
javax.servlet.ServletException: Servlet execution threw an exception
root cause
java.lang.NoClassDefFoundError: javax/servlet/http/HttpServletRequest
org.apache.commons.fileupload.servlet.ServletFileUpload.isMultipartContent(ServletFileUpload.java:68)
SimpleServlets.doPost(SimpleServlets.java:21)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
然后最后谷歌搜索,找到了一些解决方案,我一个接一个地跟着他们。
1.在WEB-INF中创建一个lib文件夹并复制commons-fileupload-1.2.2和commons-io-2.2。 但没有运气。
2.Copied commons-fileupload-1.2.2和tomons / lib中的commons-io-2.2。 但没有运气。
3.将commons-fileupload-1.2.2和commons-io-2.2添加到classpaath但没有运气。
请告诉我有什么问题。
我的代码
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.File;
import java.util.List;
import java.util.Iterator;
public class SimpleServlets extends HttpServlet {
private static final long serialVersionUID = -3208409086358916855L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
答案 0 :(得分:1)
您缺少javax.servlet.http.HttpServletRequest
,它出现在servlet-api.jar中。这是您需要在部署的解决方案中包含的那个。
查看findjar.com,它会告诉您哪些罐子包含给定的类。它无法帮助您解决所需的版本号,但它会指向正确的方向。