java.lang.IllegalStateException: getCompressingOutputStream() has already been called
public void downloadTemplate(HttpServletRequest request,HttpServletResponse response,String templatePath,String title) {
InputStream in=null;
try {
in = request.getServletContext().getResourceAsStream("/WEB-INF/xls/"+templatePath );
//判断读取文件失败,抛出异常
if(in==null){
throw new RuntimeException();
}
BufferedInputStream bin = new BufferedInputStream(in);
OutputStream out = response.getOutputStream();
byte[] buff =new byte[2048];
int len=-1;
do{
len = bin.read(buff);
out.write(buff);
}while(len>-1);
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=" + new String( title.getBytes("gb2312"), "ISO8859-1" ) + ".xls");
} catch (Exception e) {
response.reset();
response.setContentType("text/html;charset=gb2312");
PrintWriter out = null;
String url = request.getContextPath() + "/login.jhtml";
try {
out = response.getWriter();
StringBuffer buffer = new StringBuffer();
buffer.append("<script language='javascript' type='text/javascript'>");
buffer.append("alert('模版不存在,请重试!');window.top.location.href='" + url + "'");
buffer.append("</script>");
out.println(buffer.toString());
out.flush();
} catch (IOException ee) {
}finally{
if(out!=null){
out.close();
}
}
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
}
}
}
}
导致异常原因:Servlet规范说明,不能既调用 response.getOutputStream(),又调用response.getWriter(),无论先调用哪一个,在调用第二个时候应会抛出 IllegalStateException。
解决方法:
代码加入以下判断,避免同时调用response.getOutputStream(),response.getWriter()
//判断读取文件失败,抛出异常
if(in==null){
throw new RuntimeException();
}