bean中的JSF CSV下载

时间:2013-02-19 22:16:50

标签: java jsf csv download

我正在尝试以与此处相同的方式进行csv下载: How to provide a file download from a JSF backing bean?

我的回复一直在nullPointerException行投放output.write()。 bean是请求范围。关于空指针的任何想法?

    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();
    }

1 个答案:

答案 0 :(得分:0)

这里有3件事情跳出来

  1. 无法在responseComplete()上调用FacesContext,这意味着JSF将继续处理请求,并且不会影响结果。

  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();
    }
    
  4. 此外,您只需致电sos.println(s),无需在那里完成所有工作