我正在尝试以与此处相同的方式下载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件事跳出这里
-
如果不能在
FacesContext
上调用responseComplete()
,那么JSF将继续处理请求,并且不会影响结果。 -
reset()
调用是不必要的。 -
输出流应为
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)
,而无需在那里进行所有工作