bean中的JSF CSV下载

我试图以与此处相同的方式进行csv下载: 如何从JSF支持bean提供文件下载?

我的响应一直在output.write()行抛出nullPointerException 。 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(); } 

3件事情在这里跳出来

  1. 未能在FacesContext上调用responseComplete()几乎意味着JSF将继续处理请求而您不会影响结果。

  2. reset()调用是不必要的。

  3. outputstream应该是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)而无需在那里完成所有工作