Click here to Skip to main content
15,174,684 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


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

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

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, {
      // Check that we have a file upload request
      isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType("text/html"); out = response.getWriter( );
      if( !isMultipart ){
         out.println("<title>Servlet upload</title>");  
         out.println("<p>No file uploaded</p>"); 
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      // 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 );

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

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

      out.println("<title>Servlet upload</title>");  
      //while ( i.hasNext () ) 
         FileItem fi = (FileItem);
         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("\\"))) ;
               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);
         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("\\"))) ;
               file = new File( "C:/UploadedFiles/" + fileName2.substring(fileName2.lastIndexOf("\\")+1)) ;
            fi2.write( file ) ;
            out.println("Uploaded Filename: " + fileName2 + " --- saved in C:/UploadedFiles/ " + "<br>");       

      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; 

            String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
            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();
                System.out.println("Uploaded successfully !");

      catch(Exception e){
      finally {
          // close all the connections.
   }catch(Exception ex) {

   public void doGet(HttpServletRequest request, 
                       HttpServletResponse response)
        throws ServletException, {

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

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

    at UploadServlet.doPost(
    at javax.servlet.http.HttpServlet.service(
    at javax.servlet.http.HttpServlet.service(
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(
    at org.apache.catalina.core.StandardWrapperValve.invoke(
    at org.apache.catalina.core.StandardContextValve.invoke(
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(
    at org.apache.catalina.core.StandardHostValve.invoke(
    at org.apache.catalina.valves.ErrorReportValve.invoke(
    at org.apache.catalina.valves.AccessLogValve.invoke(
    at org.apache.catalina.core.StandardEngineValve.invoke(
    at org.apache.catalina.connector.CoyoteAdapter.service(
    at org.apache.coyote.http11.AbstractHttp11Processor.process(
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(
    at java.util.concurrent.ThreadPoolExecutor$

    at UploadServlet.doPost(

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.
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

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