java.lang.NullPointerException

Hello! I would be very gratefull if you could find where is my problem and how can I fix it. (java.lang.NullPointerException)

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>

UploadServlet.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.");
   } 
}
View Answers

February 17, 2012 at 2:02 PM

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)

February 17, 2012 at 5:47 PM

Problem solved! I had to use null check to the variables before using them to store in database.









Related Tutorials/Questions & Answers:
java.lang.NullPointerException
java.lang.NullPointerException  I am getting the bellow error message whenever dispaly the data from database to jsp .some times data is dispalying... the bellow error message java.lang.NullPointerException
java.lang.NullPointerException
java.lang.NullPointerException  Hello! I would be very gratefull if you could find where is my problem and how can I fix it. (java.lang.NullPointerException) index.html: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Advertisements
Error java.lang.NullPointerException hibernate - Hibernate
Error java.lang.NullPointerException hibernate  hello everybody; I'm developping a web application using Struts 1.1 , Hibernate 3.1 and Mysql , and I've got this message error: Etat HTTP 500
java.lang.NullPointerException - JSP-Servlet
java.lang.NullPointerException   ... ... ... ... function myFunc3() { var n='' if(n!=null... java.lang.NullPointerException ..................... Pls help me ... my
problem with org.apache.jasper.JasperException: java.lang.NullPointerException
problem with org.apache.jasper.JasperException: java.lang.NullPointerException  I could not find my mistake. Here is my code. Thanks in advance. <body> <% String pack_id = request.getParameter("pack_id
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException   when i click on the SUBMIT button ON,OFF window is visiable first OFF button..." java.lang.NullPointerException at NextPage$2.actionPerformed(NextPage.java:36
JBOSS Startup Problem - StandardWrapper.Throwable java.lang.NullPointerException at java.util.Hashtable.put(Hashtable.java:394)
JBOSS Startup Problem - StandardWrapper.Throwable java.lang.NullPointerException at java.util.Hashtable.put(Hashtable.java:394)  Hi Gurus!!!! :D.. I am new to Rose India and also new to JBOSS. I have a problem in JBOSS Starting
Java error java.lang.nullpointerexception
Java error java.lang.nullpointerexception       NullPointerException ...;java.lang.NullPointerException   at 
class - Java Beginners
Class java.lang.nullpointerexception  When the class java.lang.nullpointerexception occurs
Hibernate error in eclipse
: org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException) (Caused by org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused
Hibernate error in eclipse
: org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException) (Caused by org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused
Hibernate error in eclipse
: org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException) (Caused by org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused
Hibernate error in eclipse
: org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException) (Caused by org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused
Hibernate error in eclipse
: org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException) (Caused by org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused
Java Basic - Applet
Java Basic  My Applet Programs are Compiling as well as Running properly. But when I close the Applet window I am getting an Error Message as: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException and also 10
How to get the value of <html:image></html:image> - Struts
java.lang.NullPointerException Please help me how to get the value of this param into action
org.hibernate.cfg.Environment - Hibernate
: contact.hbm.xml Exception in thread "main" java.lang.NullPointerException
JSF error
JSF error  some of the users are not able to update the db. getting the error "An Error Occurred: Error calling action method of component with id CreateorManageOffer:jidjsp134312524923 Caused by: java.lang.NullPointerException
Java null pointer exception handling
is a java.lang.NullPointerException? Why do we use this exception class and when it occurs in any java...; java.lang.NullPointerException Handling NullPointerException in Java: java.lang.NullPointerException occurs when it tries to invoke a null object, at the time
Java Compilation error - Java Beginners
Java Compilation error   i wrote a simple hello world program i get this error every time please help Exception in thread "main" java.lang.NullPointerException
hibernate code - Hibernate
" java.lang.NullPointerException at mohit.tutorial.hibernate.FirstExample.main
Hibernate error - Hibernate
" java.lang.NullPointerException at roseindia.tutorial.hibernate.FirstExample.main
struts problem
struts problem  java.lang.NullPointerException: Module 'null' not found. org.apache.struts.taglib.TagUtils.getModuleConfig(TagUtils.java:755) org.apache.struts.taglib.TagUtils.getModuleConfig(TagUtils.java:735
executing Hibernate application
" java.lang.NullPointerException at FirstExample.main(FirstExample.java:37
Jsp error when i run this a jsp file
Jsp error when i run this a jsp file  hi I got this error when i run the jsp file in IDE and outside also please help me java.lang.NullPointerException org.apache.jsp.insertjsp.jspInit(insert_jsp.java:22
Can anybody tell me how to resolve this issue?
:568) java.lang.NullPointerException at hdox.HL7FileParseUtilityADT.processFile
Struts2
Struts2  java.lang.NullPointerException org.apache.struts2.impl.StrutsActionProxy.getErrorMessage(StrutsActionProxy.java:69) com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:185
Error in checking null value in string
Error in checking null value in string  Error in checking null value in string Hi am getting Exception : java.lang.NullPointerException in the following code: String registerno=null; registerno=request.getParameter("registerno
connecting to a database dynamically - JSP-Servlet
. exception org.apache.jasper.JasperException: java.lang.NullPointerException... java.lang.NullPointerException org.apache.jsp.abc_jsp._jspService(abc_jsp.java:72
Delete HQL query - Hibernate
initialize the log4j system properly. java.lang.NullPointerException
java runtime error - JDBC
java runtime error  sir when i m running the jsp connectivity program it is giving the error as follows:' java.lang.NullPointerException at jsp_servlet.__resplogin._jspService(__resplogin.java:237
Regarding Login application program
: java.lang.NullPointerException...(ReplyHeaderFilter.java:96) root cause ADS_TO_REPLACE_4 java.lang.NullPointerException... it is giving java.lang.NullPointerException exception.ADS_TO_REPLACE_6 Please download
Unhandled Exception in Thread
java.lang.NullPointerException with message: null [thrower("not") done] Check "... : java.lang.nullpointerexception java.lang.nullpointerexception is thrown by JVM when a programmer... java.lang.nullpointerexception: We have used a class javaerrornullpointerexception. string.charAt
java - Java Beginners
]); } } } I am getting Exception in thread "main" java.lang.NullPointerException
Struts-Hibernate-Integration - Hibernate
java.lang.NullPointerException roseindia.web.SearchTutorialAction.execute(Unknown Source
Mockstrutstest case in Weblogic - Maven
loading web.xml - class java.lang.NullPointerException : null
Nullpointer Exception - JSP-Servlet
cause java.lang.NullPointerException
JSF Select one menu - Framework
Design Editor, Error messages from the component:java.lang.NullPointerException
java,eclipse - Swing AWT
// (version 1.5 : 49.0, super bit) public class java.lang.NullPointerException
jsp
java.lang.NullPointerException
jsp
java.lang.NullPointerException
Why do the slashes change when the console gives me the error?
) java.lang.NullPointerException at javax.imageio.ImageIO.write(ImageIO.java:1523
jsp error
. exception org.apache.jasper.JasperException: java.lang.NullPointerException...) root cause java.lang.NullPointerException org.apache.jsp.first<em>
Context binding
factory specified in hashtable {} [Root exception is java.lang.NullPointerException... by: java.lang.NullPointerException at javax.naming.spi.NamingManager.getInitialContext
http status 500 error in tomcat 6 while using eclipse helios
this request. exception java.lang.NullPointerException... exception java.lang.NullPointerException
http status 500 error in tomcat 6 while using eclipse helios
this request. exception java.lang.NullPointerException... exception java.lang.NullPointerException
http status 500 error in tomcat 6 while using eclipse helios
this request. exception java.lang.NullPointerException... exception java.lang.NullPointerException
http status 500 error in tomcat 6 while using eclipse helios
this request. exception java.lang.NullPointerException... exception java.lang.NullPointerException
http status 500 error in tomcat 6 while using eclipse helios
this request. exception java.lang.NullPointerException... exception java.lang.NullPointerException
error
error  java.lang.NullPointerException at com.knkglob.service.LoginServiceImpl.checkLogin(LoginServiceImpl.java:26) at com.knkglob.controller.LoginController.processForm(LoginController.java:58