-4

I am trying to create a Servlet which will accept a simple POST request. I followed the method as described here, and started the server, it dishes out the page with the text Hello friend! as expected.

So next, I replaced the doGet method with doPost as described here. This is my code (most of the code is commented out):

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);
//          }
        }
    }
}

The code is failing at the ServletFileUpload upload = new ServletFileUpload(factory); line. This is the error stack I am getting:

enter image description here

How do I fix this error?

Edit: Eclipse shows an error log:

------
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
SexyBeast
  • 7,913
  • 28
  • 108
  • 196
  • Check if this question is useful for you: http://stackoverflow.com/questions/32471642/multiple-file-upload/32472421#32472421 – Ravindra babu Oct 22 '15 at 17:54
  • Error stack has nothing to do with code posted so far. Tomcat just failed to start (usually due to severe webapp configuration error). It didn't even had chance to invoke the servlet. Post the full startup log (please not in a screenshot, that's not friendly for searchbots, just post it in a code block). – BalusC Oct 22 '15 at 19:55
  • Can you tell me where do I get the full startup log? The one whose screenshot I posted? That vanishes immediately after it shows up (I screenshot it with great precision of time)... – SexyBeast Oct 23 '15 at 07:35
  • Eclipse doesn't keep a log file. Console should just stay if you gently start/stop the server via *Servers* tab instead of doing "Run As" on project/servlet. Nonetheless, as to your ultimate goal of uploading a file using JSP+Servlet, didn't you found this Q during research here? http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet/ You appear to be using Tomcat 8 and yet you're grabbing legacy Apache Commons FileUpload. – BalusC Oct 23 '15 at 10:23
  • Yep, I a doing this via Servers tab, i.e. Window->Views->Servers, and then clicking the start button, and then that console log shows up momentarily before vanishing, and then Eclipse alerts that it couldn't start the server. I looked into the answer, but not able to understand it. Where do I look for that artifact? – SexyBeast Oct 23 '15 at 11:55
  • My previous link only answers how to properly implement file upload with JSP+Servlet, not how to solve your current problem with Tomcat+Eclipse (otherwise, I'd have posted it as an answer instead of as a comment). So, if you have the chance to throw away your current broken project and create a new project the right way, then you could just follow the guidelines in that link. – BalusC Oct 23 '15 at 12:37
  • Now, coming back to your current problem, I hope that you by now realize that this all has completely nothing to do with the *"Java Servlet post request not working with ServletFileUpload"* as your current question states. The Eclipse error log which you just edited in is not relevant to Tomcat's startup problem. I suggest to export the project to a WAR file, manually put it in Tomcat's /webapps folder and manually start Tomcat via /bin/startup. It writes the startup log to a persistent file in /logs folder which you could always read back later on. – BalusC Oct 23 '15 at 12:38

1 Answers1

3
  1. Your servlet is not thread-safe.

    The doPost() method can be called simultaneously several times to serve several incoming requests. There should be no fields in the servlet class that depend on request data.

    In your case you have "isMultipart" both as a field and as a local variable. There should be no such field.

  2. Read the Java Servlet specification. Tomcat 8 implements Servlet 3.1. Its chapter "3.2 File upload" covers the file upload API.

    Using Apache Commons Fileupload is possible, but why bother if there is official Servlet API for this task?

  3. That NullPointerException stacktrace during shutdown of Tomcat is irrelevant to your problem.

    Your Test servlet is not in that stacktrace. Especially "The code is failing at the ServletFileUpload upload = new ServletFileUpload(factory); line." statement in your question has no evidence for it. Something else is happening.

    Yep, I a doing this via Servers tab, i.e. Window->Views->Servers, and then clicking the start button, and then that console log shows up momentarily before vanishing

    When Eclipse starts Tomcat (as well as any other java application), it opens a Console view for it.

    If you cannot find the Console view onscreen, you can use Window > Perspective > Reset Perspective to reset layout of your windows and then open it manually through Window > Show View > Console. See Eclipse Workbench Tutorial (also available locally via Help menu) and also its page on Console view

Konstantin Kolinko
  • 3,854
  • 1
  • 13
  • 21
  • The code is failing at the ServletFileUpload upload = new ServletFileUpload(factory); line." - I said that because if I comment out that line the server starts as expected. – SexyBeast Oct 28 '15 at 17:18
  • Your code works for me both with and without that line, using latest Tomcat 8, commons-io-2.4.jar, commons-fileupload-1.3.1.jar. Look for a problem somewhere else. You still haven't provided the actual error message. – Konstantin Kolinko Oct 29 '15 at 15:39