我正在尝试创建一个Servlet,它将接受一个简单的POST请求。我按照here中所述的方法进行操作,并启动了服务器,它在页面上显示了文本Hello Hello!如预期的那样。

因此,接下来,我按照here所述用doGet替换了doPost方法。这是我的代码(大多数代码已被注释掉):

package com.file.upload;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.activation.MimetypesFileTypeMap;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;


/**
 * Servlet implementation class HelloServlet
 */
@WebServlet("/Test")
public class Test extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private boolean isMultipart;
    private String filePath;
    private int maxFileSize = 50 * 1024;
    private int maxMemSize = 4 * 1024;
    private File file ;

    public void init( ){
        // Get the file location where it would be stored.
        filePath =
                getServletContext().getInitParameter("file-upload");
    }

    public void doPost(HttpServletRequest request,
            HttpServletResponse response)
                    throws ServletException, java.io.IOException {
        // Check that we have a file upload request
        isMultipart = ServletFileUpload.isMultipartContent(request);
        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter( );
        if( !isMultipart ){
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
            return;
        }
        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 + "/fileuploads");
//                      if (!path.exists()) {
//                          boolean status = path.mkdirs();
//                      }
//
//                      File uploadedFile = new File(path + "/" + fileName);
//                      item.write(uploadedFile);
//                  }
//              }
//          } catch(Exception ex) {
//              System.out.println(ex);
//          }
        }
    }
}


代码在ServletFileUpload upload = new ServletFileUpload(factory);行处失败。这是我得到的错误堆栈:

java - Java Servlet发布请求不适用于ServletFileUpload-LMLPHP

如何解决此错误?

编辑:Eclipse显示错误日志:

------
STATUS
------
pluginId            org.eclipse.wst.server.core
pluginVersion       1.6.100.v201505132000
code                0
severity            4
message             HIDDEN
fingerprint         d680f315

Exception:org.eclipse.epp.internal.logging.aeri.ui.log.StandInStacktraceProvider$StandInException: HIDDEN
     at org.eclipse.core.internal.jobs.JobManager.endJob(JobManager.java:701)
     at org.eclipse.core.internal.jobs.WorkerPool.endJob(WorkerPool.java:105)
     at org.eclipse.core.internal.jobs.Worker.run(Worker.java:72)

------
REPORT
------
anonymousId         5eca4a19-ce2d-4492-b01b-0011f98c45ff
name                My Name
email
comment
eclipseBuildId      4.5.0.I20150603-2000
eclipseProduct      org.eclipse.epp.package.jee.product
javaRuntimeVersion  1.8.0_51-b16
osgiWs              cocoa
osgiOs              MacOSX
osgiOsVersion       10.10.5
osgiArch            x86_64
logMessage          false
ignoreSimilar       false

-------
BUNDLES
-------
name                org.eclipse.core.jobs
version             3.7.0.v20150330-2103

最佳答案

您的servlet不是线程安全的。

可以同时调用doPost()方法多次,以服务于多个传入请求。 Servlet类中不应有任何依赖于请求数据的字段。

在您的情况下,您同时将“ isMultipart”作为字段和局部变量。不应有此类字段。
阅读Java Servlet specification。 Tomcat 8实现了Servlet 3.1。其章节“ 3.2文件上载”涵盖了文件上载API。

可以使用Apache Commons Fileupload,但是如果有用于此任务的官方Servlet API,为什么还要麻烦呢?
Tomcat关闭期间的NullPointerException stacktrace与您的问题无关。

您的测试servlet不在该堆栈跟踪中。特别是“代码在ServletFileUpload upload = new ServletFileUpload(factory);行失败。”您的问题中的陈述没有证据。其他事情正在发生。


  是的,我是通过“服务器”选项卡(即“窗口”->“视图”->“服务器”)执行此操作,然后单击“开始”按钮,然后该控制台日志会暂时消失


当Eclipse启动Tomcat(以及任何其他Java应用程序)时,它将为其打开控制台视图。

如果在屏幕上找不到控制台视图,则可以使用“窗口”>“透视图”>“重置透视图”重置窗口的布局,然后通过“窗口”>“显示视图”>“控制台”手动将其打开。请参见Eclipse Workbench Tutorial(也可通过“帮助”菜单在本地获得)及其在Console view上的页面

09-25 20:42