Click here to Skip to main content
15,885,537 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I would be very gratefull if you could find where is my problem and how can I fix it. (java.lang.NullPointerException)

here is my html from where I get a textfield and I upload 2 files

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>Insert title here</title>
    </head>
    <body>
    <h3>File Upload:</h3>
    <form action="UploadServlet" method="post"
                            enctype="multipart/form-data">
    <br><br><br><br><br>
    Insert your ID (marca) - ex: 101358 
    <br>
    <input type="text" name="rid" size="40" />
    <br><br>
    Browse your files:
    <br>
    <input type="file" name="file" size="30" />
    <br />
    <br/>
    <input type="file" name="file" size="30" />
    <br />
    <br>
    <input type="submit" value="Upload File" />
    </form>
    </body>
    </html>



in this servlet I save the uploaded files into a specific folder and after that I am connecting to a database where I want to store the string got from html and the file paths from the uploaded files

UploadServlet.java

Java
public class UploadServlet 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;
      }
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:\\temp"));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );

      try{ 
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);

      // Process the uploaded file items
      Iterator i = fileItems.iterator();

      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");  
      out.println("</head>");
      out.println("<body>");
      //while ( i.hasNext () ) 
      //{
         FileItem fi = (FileItem)i.next();
         if ( !fi.isFormField () )  
         {
            // Get the uploaded file parameters
            //String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            //String contentType = fi.getContentType();
            //boolean isInMemory = fi.isInMemory();
            //long sizeInBytes = fi.getSize();
            // Write the file
            if( fileName.lastIndexOf("\\") >= 0 ){
               file = new File( "C:/UploadedFiles/" + fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
               file = new File( "C:/UploadedFiles/" + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            fi.write( file ) ;
            out.println("Uploaded Filename: " + fileName + " --- saved in C:/UploadedFiles/ " + "<br>");
         }

         FileItem fi2 = (FileItem)i.next();
         if ( !fi2.isFormField () ) 
         {
            // Get the uploaded file parameters
            //String fieldName2 = fi2.getFieldName();
            String fileName2 = fi2.getName();
            //String contentType2 = fi2.getContentType();

            //boolean isInMemory = fi2.isInMemory();
            //long sizeInBytes = fi2.getSize();
            // Write the file
            if( fileName2.lastIndexOf("\\") >= 0 ){
               file = new File( "C:/UploadedFiles/" + fileName2.substring( fileName2.lastIndexOf("\\"))) ;
            }else{
               file = new File( "C:/UploadedFiles/" + fileName2.substring(fileName2.lastIndexOf("\\")+1)) ;
            }
            fi2.write( file ) ;
            out.println("Uploaded Filename: " + fileName2 + " --- saved in C:/UploadedFiles/ " + "<br>");       
         }

      //}
      out.println("</body>");
      out.println("</html>");     
      String idmarca = request.getParameter("rid");

      String itemName1 = fi.getName();
      String path1 = new String("C:\\UploadedFiles\\" + itemName1.substring(itemName1.lastIndexOf("\\")));

      String itemName2 = fi2.getName();
      String path2 = new String("C:\\UploadedFiles\\" + itemName2.substring(itemName2.lastIndexOf("\\")));
      Connection con = null;
      PreparedStatement ps; 

      try{      
            String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
            Class.forName(driver);
            String db = "jdbc:odbc:upload";
            con = DriverManager.getConnection(db, "", "");  
            String sql = "INSERT INTO file1(marca,file1,file2) VALUES(?, ?, ?)";            
            ps = con.prepareStatement(sql);              

            ps.setString(1, idmarca);
            ps.setString(2, path1);
            ps.setString(3, path2);
            int s = ps.executeUpdate();
            if(s>0){
                System.out.println("Uploaded successfully !");
            }
            else{
                System.out.println("Error!");
            }

      }
      catch(Exception e){
          e.printStackTrace();
      }
      finally {
          // close all the connections.
          //ps.close();
          //con.close();
      }
   }catch(Exception ex) {
       ex.printStackTrace();
   }  
   }   


   public void doGet(HttpServletRequest request, 
                       HttpServletResponse response)
        throws ServletException, java.io.IOException {

        throw new ServletException("GET method used with " + getClass( ).getName( )+": POST method required.");
   } 
}



I think that the NPE is somewhere in the database connection.

java.lang.NullPointerException
    at UploadServlet.doPost(UploadServlet.java:126)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)
Posted

java.lang.NullPointerException
    at UploadServlet.doPost(UploadServlet.java:126)


says that there is a nullpointer popping at the line 126 in the method doPost() of the class UploadServlet.

So you use a IDE? do so. and activate the line numbering. Also set a break point on NullpointerException and use Debug mode for running that service - you will figure where a value is null.
 
Share this answer
 
Comments
mamba1988 17-Feb-12 7:18am    
Problem solved! I had to use null check to the variables before using them to store in database. Thanks!
OK, my problem is in line String idmarca = request.getParameter("rid"); it gets the text from the html textfield. Before adding this textfield I was able to save the file paths of the uploaded files
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900