1

我在这里收到空指针异常:

List fileItems = upload.parseRequest(req);

如果文件中的行数大于大约 2000 行,就会发生这种情况,因为我可以上传超过 1000 行的文件。有人请帮帮我。表格如下。

<form name="fos_picks" id="fos_picks" action="<%=path%>/fos_upld" method="post" enctype="multipart/form-data" >

<br/><br/><br/><br/>
<p align="center">
    <input type="file" name="file" size="50" /><br/>
    <br/>
    <input type="submit" class="buttons" value="Upload File" />
    </p>
</form>

上传控制器代码...

 package file_proc;
import DBConn.DBConn;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.PreparedStatement;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


@WebServlet(name="file_upld", urlPatterns = {"/file_upld"}) 

public class file_upld extends HttpServlet {

   private boolean isMultipart;
   private String filePath;
   private int maxFileSize = 50 * 1024;
   private int maxMemSize = 10 * 1024;
   private File file ;

/*   public void init( ){
      // Get the file location where it would be stored.
      filePath = 
             getServletContext().getInitParameter("file-upload"); 
   }*/
    @Override
   public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, java.io.IOException {
      // Check that we have a file upload request
       java.io.PrintWriter out = res.getWriter( );
    //   out.println("entered");
      isMultipart = ServletFileUpload.isMultipartContent(req);

      res.setContentType("text/html");

      if( !isMultipart ){
         out.println("!multipart");
         System.out.println("here");
         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 );
 ServletContext servletContext = getServletContext();
    String path = servletContext.getRealPath("/");
     BufferedReader br=null;
     String fileName="";
     DBConn db = new DBConn();

      try{ 
      // Parse the request to get file items.
          System.out.println("here1"+req);
      List fileItems = upload.parseRequest(req);

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

/*      out.println("<html>");
      out.println("<head>");
      out.println("<title>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();
            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:/Temp/" + 
               fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
               file = new File( "c:/Temp/"+ 
               fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            if(!file.exists())
            {
                File fold=new File(file.getParent());
                fold.mkdirs();
            }
            fi.write( file ) ;
            System.out.println("Uploaded Filename: " + fileName + "<br>");
         }
      }
      }catch(Exception ce)
      {
            out.println("<font size='30' color='red'>Error Code 016</font>");
        //out.println("Exception1: "+ce);
      }
 //read uploaded file and insert into table********************************************  

    //      String newline = System.getProperty("line.separator");
//  File file = new File(path+"//"+fileName);
            //  file.createNewFile();
try{

    if(file.isFile())
    {
         br = new BufferedReader(new FileReader(file));
    String str="";
    String temp[]=null;


        file.canWrite();
        file.canRead();
        file.setWritable(true);

        db.conn.setAutoCommit(false);
        while((str=br.readLine())!=null)
                    {
                        temp=str.split("    ");

                //      PreparedStatement ps = db.conn.prepareStatement("INSERT INTO file_proc VALUES(?,?,?,?,?,?,?,?,?,STR_TO_DATE(?,'%m/%d/%Y'))");
                        PreparedStatement ps = db.conn.prepareStatement("INSERT INTO file_proc(run_date,zone,location,bank,file_type,num_rec,ex_sett_date,ex_stat_date) "
                                                        + "VALUES(STR_TO_DATE(?,'%m/%d/%Y'),?,?,?,?,?,STR_TO_DATE(?,'%m/%d/%Y'),STR_TO_DATE(?,'%m/%d/%Y'))");
                        ps.setString(1,temp[0]);
                        ps.setString(2,temp[1]);
                        ps.setString(3,temp[2]);
                        ps.setString(4,temp[3]);
                        ps.setString(5,temp[4]);
                        ps.setInt(6,Integer.parseInt(temp[5]));
                        ps.setString(7,temp[6]);
                        ps.setString(8,temp[7]);
                        ps.executeUpdate();
                        ps.close();     

                    }   
                    db.conn.commit();
                    db.conn.setAutoCommit(true);
                    db.conn.close();
                    br.close(); 
        file.delete();  

       //  RequestDispatcher rd = req.getRequestDispatcher("./status/status.jsp");
        //  rd.forward(req, res);
          out.print("success");
     //     out.println("</html>");
    }
    else
    {
        out.println(file+" is not a file");
    }           

   }catch(Exception ex) {
    out.println("file name= "+fileName);
      // out.println("DBEX= "+ex );
        out.println("<font size='30' color='red'>Error Code 017 - Recommended date format = m/d/yyyy.</font>");
        out.println("<font size='30' color='red'>Check the column order</font>"+ex);    
      //file.delete();  
     //  RequestDispatcher rd = req.getRequestDispatcher("./status/error.jsp");
//  rd.forward(req, res);
   }finally{
                    try{
                        db.conn.close();
                        br.close();
                    }catch(Exception e){}
                }
   }
    @Override
   public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, java.io.IOException {

       doPost(request, response);  
   } 
}

** * *这是表格* ** * **

<form name="file_proc" id="file_proc" method = "post" action="../file_upld" enctype="multipart/form-data">
    <br/><br/><br/><br/>
    <p align="center">
<input type="file" id="file" name="file" size="50" /><br/>
<br/>
<input type="submit" class="buttons" value="Upload File" />br/><br/><br/>
     </p>
</form>

上传控制器代码...

 package file_proc;
import DBConn.DBConn;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.PreparedStatement;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


@WebServlet(name="file_upld", urlPatterns = {"/file_upld"}) 

public class file_upld extends HttpServlet {

   private boolean isMultipart;
   private String filePath;
   private int maxFileSize = 50 * 1024;
   private int maxMemSize = 10 * 1024;
   private File file ;

/*   public void init( ){
      // Get the file location where it would be stored.
      filePath = 
             getServletContext().getInitParameter("file-upload"); 
   }*/
    @Override
   public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, java.io.IOException {
      // Check that we have a file upload request
       java.io.PrintWriter out = res.getWriter( );
    //   out.println("entered");
      isMultipart = ServletFileUpload.isMultipartContent(req);

      res.setContentType("text/html");

      if( !isMultipart ){
         out.println("!multipart");
         System.out.println("here");
         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 );
 ServletContext servletContext = getServletContext();
    String path = servletContext.getRealPath("/");
     BufferedReader br=null;
     String fileName="";
     DBConn db = new DBConn();

      try{ 
      // Parse the request to get file items.
          System.out.println("here1"+req);
      List fileItems = upload.parseRequest(req);

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

/*      out.println("<html>");
      out.println("<head>");
      out.println("<title>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();
            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:/Temp/" + 
               fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
               file = new File( "c:/Temp/"+ 
               fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            if(!file.exists())
            {
                File fold=new File(file.getParent());
                fold.mkdirs();
            }
            fi.write( file ) ;
            System.out.println("Uploaded Filename: " + fileName + "<br>");
         }
      }
      }catch(Exception ce)
      {
            out.println("<font size='30' color='red'>Error Code 016</font>");
        //out.println("Exception1: "+ce);
      }
 //read uploaded file and insert into table********************************************  

    //      String newline = System.getProperty("line.separator");
//  File file = new File(path+"//"+fileName);
            //  file.createNewFile();
try{

    if(file.isFile())
    {
         br = new BufferedReader(new FileReader(file));
    String str="";
    String temp[]=null;


        file.canWrite();
        file.canRead();
        file.setWritable(true);

        db.conn.setAutoCommit(false);
        while((str=br.readLine())!=null)
                    {
                        temp=str.split("    ");

                //      PreparedStatement ps = db.conn.prepareStatement("INSERT INTO file_proc VALUES(?,?,?,?,?,?,?,?,?,STR_TO_DATE(?,'%m/%d/%Y'))");
                        PreparedStatement ps = db.conn.prepareStatement("INSERT INTO file_proc(run_date,zone,location,bank,file_type,num_rec,ex_sett_date,ex_stat_date) "
                                                        + "VALUES(STR_TO_DATE(?,'%m/%d/%Y'),?,?,?,?,?,STR_TO_DATE(?,'%m/%d/%Y'),STR_TO_DATE(?,'%m/%d/%Y'))");
                        ps.setString(1,temp[0]);
                        ps.setString(2,temp[1]);
                        ps.setString(3,temp[2]);
                        ps.setString(4,temp[3]);
                        ps.setString(5,temp[4]);
                        ps.setInt(6,Integer.parseInt(temp[5]));
                        ps.setString(7,temp[6]);
                        ps.setString(8,temp[7]);
                        ps.executeUpdate();
                        ps.close();     

                    }   
                    db.conn.commit();
                    db.conn.setAutoCommit(true);
                    db.conn.close();
                    br.close(); 
        file.delete();  

       //  RequestDispatcher rd = req.getRequestDispatcher("./status/status.jsp");
        //  rd.forward(req, res);
          out.print("success");
     //     out.println("</html>");
    }
    else
    {
        out.println(file+" is not a file");
    }           

   }catch(Exception ex) {
    out.println("file name= "+fileName);
      // out.println("DBEX= "+ex );
        out.println("<font size='30' color='red'>Error Code 017 - Recommended date format = m/d/yyyy.</font>");
        out.println("<font size='30' color='red'>Check the column order</font>"+ex);    
      //file.delete();  
     //  RequestDispatcher rd = req.getRequestDispatcher("./status/error.jsp");
//  rd.forward(req, res);
   }finally{
                    try{
                        db.conn.close();
                        br.close();
                    }catch(Exception e){}
                }
   }
    @Override
   public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, java.io.IOException {

       doPost(request, response);  
   } 
}

** * *这是表格* ** * **

<form name="file_proc" id="file_proc" method = "post" action="../file_upld" enctype="multipart/form-data">
    <br/><br/><br/><br/>
    <p align="center">
<input type="file" id="file" name="file" size="50" /><br/>
<br/>
<input type="submit" class="buttons" value="Upload File" />br/><br/><br/>
     </p>
</form>

这是 log4j 的东西,它显示了 filter.java 的错误,我没有在当前的 servlet 中使用它。

[错误] 29:05(file_upld.java:doPost:172)失败!

java.lang.NullPointerException at file_proc.file_upld.doPost(file_upld.java:120) at javax.servlet.http.HttpServlet.service(HttpServlet.java:641) at javax.servlet.http.HttpServlet.service(HttpServlet.java: 722) 在 org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) 在 org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) 在 filter.filter.doFilter(filter.java :16) 在 org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) 在 org.apache.catalina.core 的 org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)。 StandardWrapperValve.invoke(StandardWrapperValve.java:225) 在 org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)在org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)在org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)在org.apache.catalina.valves.ErrorReportValve .invoke(ErrorReportValve.java:98) 在 org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927) 在 org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) 在 org. apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol. java:565) 在 org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307) 在 java.util.concurrent。ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) 在 java.lang.Thread.run(Thread.java:722)

这里是 filter.javapackage 过滤器;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;

public class filter implements Filter{

    private FilterConfig config=null;
    @Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException 
{
    HttpServletResponse hsr = (HttpServletResponse) res;
    hsr.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
    hsr.setHeader("Pragma", "no-cache"); // HTTP 1.0.
    hsr.setDateHeader("Expires", 0); // Proxies.
    chain.doFilter(req, res);
}
    @Override
    public void destroy() { }
    @Override
  public void init(FilterConfig config) {
  this.config = config;
  }
}
4

1 回答 1

3

您的具体问题是由糟糕的异常处理和与控制器的紧密耦合视图引起的。

从代码中过滤掉噪音后,大致如下:

File file = null;

try {
    // ... 
    file = new File(...);
    // ... 
} catch (Exception e) {
    out.println("...");
}

try {
    if (file.isFile())
        // ...
    } else {
        // ...
    }
} catch (Exception e) {
    out.println("...");
}

NullPointerException扔在与if (file.isFile())块的直线上。因此,这意味着第一个try块引发了异常,因此留下了fileas null

问题的原因有两个:

  1. 第一个try块不是在异常时从 servlet 方法返回,而是错误地继续代码流。
  2. 如果不是,第二个try块不会事先检查。filenull

然而,你的具体问题要大得多。您完全吞下异常并打印不相关的 HTML 代码,而不是将它们抛出和/或记录异常。

按如下方式替换您的 catch 块:

} catch (Exception e) {
    throw new ServletException(e);
}

默认情况下,这种方式将记录异常并在 HTTP 500 错误页面中以完整的方式显示异常,并与堆栈跟踪一起完成。堆栈跟踪为您提供了丰富的信息来了解问题并解决问题。


与具体问题无关,代码中还有许多其他概念和设计错误,但迄今为止与具体问题没有直接关系。但是,我建议暂停一下并阅读一些理智的 Servlet 书籍/教程/资源。这段代码似乎只是根据在 Google 中找到的片段拼凑而成,而不是经过深思熟虑的编写。第一步是了解 servlet 是如何工作的:servlet 是如何工作的?实例化、会话、共享变量和多线程

于 2012-10-11T19:53:42.427 回答