1

I am trying to do a csv download in the same fashion as here: How to provide a file download from a JSF backing bean?

My response keeps throwing a nullPointerException at the output.write() line. The bean is of the request scope. Any thoughts as to the null pointer?

    try
    {
        //submitForm();
        FacesContext fc = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

        response.reset();
        response.setContentType("text/csv"); 
        //response.setContentLength(contentLength); 
            response.setHeader ( "Content-disposition", "attachment; filename=\"Reporting-" + 
                    new Date().getTime() + ".csv\"" );

        OutputStream output = response.getOutputStream();
        String s = "\"Project #\",\"Project Name\",\"Product Feature(s)\",";
        s+="\"Project Status\",";
        s+="\"Install Type\",";
        s+="\"Beta Test\",\"Beta Test New/Updated\",";
        s+="\"Production\",\"Production New/Updated\",";
        s+="\n";
        InputStream is = new ByteArrayInputStream( s.getBytes("UTF-8") );
        int nextChar;

         while ((nextChar = is.read()) != -1) 
         {
            output.write(nextChar);
         }
         output.close();

    }
    catch ( IOException e )
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
4

1 回答 1

0

3件事在这里跳出来

  1. 几乎没有调用意味着 JSF 将responseComplete()继续FacesContext处理请求并且您不会影响结果。

  2. reset()通话是不必要的。

  3. 输出流应该是类型ServletOutputStream

    请尝试以下代码段

    try
    {
    //submitForm();
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
    
    
    response.setContentType("text/csv"); 
    fc.responseComplete();
    //response.setContentLength(contentLength); 
        response.setHeader ( "Content-disposition", "attachment; filename=\"Reporting-" + 
                new Date().getTime() + ".csv\"" );
    
    ServletOutputStream output = response.getOutputStream();
    String s = "\"Project #\",\"Project Name\",\"Product Feature(s)\",";
    s+="\"Project Status\",";
    s+="\"Install Type\",";
    s+="\"Beta Test\",\"Beta Test New/Updated\",";
    s+="\"Production\",\"Production New/Updated\",";
    s+="\n";
    InputStream is = new ByteArrayInputStream( s.getBytes("UTF-8") );
    int nextChar;
    
     while ((nextChar = is.read()) != -1) 
     {
        output.write(nextChar);
     }
        output.flush();
    
     output.close();
    
    }
    catch ( IOException e )
    {
     // TODO Auto-generated catch block
        e.printStackTrace();
    }
    

此外,您可以直接拨打电话sos.println(s),而无需您在那里进行的所有工作

于 2013-02-20T00:28:11.083 回答