jsp关于respose.getOutputStream()异常的解决方案

     由于jsp隐式调用和respose.getOutputStream()显示调用,都都用到了jsp内置对象,如果不加处理,会报错为"....called"。

   解决方案分两种:(1)如果是一般纯jsp嵌入式的java代码,则在respose.getOutputStream()的前面将out重置,即加上 

   out.clear();
   out = pageContext.pushBody();

 

这两句即可。

(2)如果是struts2或者struts1等架构,则只需要在调用out前,加上out.flash(),即可。

下面举个jsp例子,直接放tomcat或下可以跑

写道
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ page language="java" import="java.io.*,java.util.zip.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'testZip.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
<%
out.clear();
out = pageContext.pushBody();

//找到后台文件夹
ZipOutputStream zos = null;
BufferedReader in = null;
//String fileName = "d:\\test1.csv";
String srcDirectoryName = "e:\\test";
zos = new ZipOutputStream(response.getOutputStream());
OutputStreamWriter writer = new OutputStreamWriter(zos);
try {
File srcDirectory = new File(srcDirectoryName);
if (!srcDirectory.isDirectory()) {
return;
}
String filename = "users.zip";
response.setHeader("content-disposition",
"attachment; filename=" + filename);
response.setCharacterEncoding("UTF-8");
// 不设置ContentType的话会乱码
response.setContentType("application/zip");
//如果文件夹存在,那么把文件夹里面的文件全部读进zip里面
String[] srcFileNames = srcDirectory.list();
if (0 == srcFileNames.length) {
return;
}
for (int i = 0; i < srcFileNames.length; i++) {
//如果存在文件则写
String srcFileName = srcFileNames[i];
String srcFileAllName = srcDirectoryName + "\\"
+ srcFileName;
File file = new File(srcFileAllName);
if (file.isFile()) {
ZipEntry zipEntry = new ZipEntry(srcFileName);
in = new BufferedReader(new FileReader(srcFileAllName));
zos.putNextEntry(zipEntry);
int ch;
//当压缩过程未结束时继续读写
while ((ch = in.read()) != -1) {
zos.write(ch);
System.out.println(ch);
}
in.close();
in = null;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != in) {
in.close();
}
if (null != zos) {
zos.close();
}
if (null != writer) {
writer.close();
}
}
%>

</body>
</html>

 以上需要注意两点:(1)先清理out

                           (2)文件夹下的文件起名最好是英文和数字,不然文件名有乱码。

你可能感兴趣的:(OutputStream)