`
Luob.
  • 浏览: 1592378 次
  • 来自: 上海
社区版块
存档分类
最新评论

解决getOutputStream() has already been called for this response

阅读更多
java.lang.IllegalStateException: getOutputStream() has already been called for this response

//strut2 导出excel


//解决问题的代码
HSSFWorkbook workbook=productEcel(list,partTimer);
				response.reset();
				response.setContentType("contentType=application/vnd.ms-excel");
				response.setHeader("Content-disposition","attachment;filename="+URLEncoder.encode("统计.xls","utf-8")); 
				workbook.write(response.getOutputStream());
				response.flushBuffer();



//出现异常的原因
产生这样的异常原因:是web容器生成的servlet代码中有out.write(""),这个和JSP中调用的response.getOutputStream()产生冲突.即Servlet规范说明,不能既调用response.getOutputStream(),又调用response.getWriter(),无论先调用哪一个,在调用第二个时候应会抛出IllegalStateException,因为在jsp中,out变量实际上是通过response.getWriter得到的,你的程序中既用了response.getOutputStream,又用了out变量,故出现以上错误。



//导出 excel
public String exportRedactor(){
		HttpServletRequest request =this.getRequest();
		HttpServletResponse response=null;
		FbbServiceClient service=null;
		ManagerUser user= (ManagerUser)request.getSession(true).getAttribute(Constants.SESSION_USER);
		InputStream is = null;
		PrintWriter out=null;
		try {
			method="";
			response=this.getResponse();
			response.setCharacterEncoding("utf-8");
			
			service=new FbbServiceClient();
			FbbService.Client client=service.open();
			if(partTimer == null)
				partTimer = new PartTimer();
			partTimer.setSourceId(2);
			List<PartTimer> list = client.getStatisticsPartTimer(user.getId(), user.getSignature(), partTimer);
			String result="";
			
			if(list==null || list.size()<=0){
				request.setAttribute("msg","没有数据需要导出");
				return SUCCESS; 
			}else{HSSFWorkbook workbook=productEcel(list,partTimer);
				response.reset();
				response.setContentType("contentType=application/vnd.ms-excel");
				response.setHeader("Content-disposition","attachment;filename="+URLEncoder.encode("统计.xls","utf-8")); 
				workbook.write(response.getOutputStream());
				response.flushBuffer();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("msg","导出数据出现异常");
			logger.error("errorcode ::: " + e.getMessage(), e);
		}finally{
			if(service!=null)
				service.close();
			if(out!=null){
				try {
					out.close();
				} catch (Exception e) {
					logger.error("errorcode ::: " + e.getMessage(), e);
				}
			}
			
			if(is!=null){
				try {
					is.close();
				} catch (Exception e) {
					logger.error("errorcode ::: " + e.getMessage(), e);
				}
			}
		}
		return NONE;



private HSSFWorkbook productEcel(List<PartTimer> list,PartTimer partTimer) throws Exception {

		// 创建工作表和标题
		HSSFWorkbook workbook = null;
		try {
			workbook = new HSSFWorkbook();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		// 定义字体
		HSSFFont celltbnamefont = workbook.createFont();
		celltbnamefont.setFontHeightInPoints((short) 12); // 字体大小
		celltbnamefont.setColor((short) (HSSFFont.COLOR_NORMAL)); // 颜色
		celltbnamefont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 粗体
		

		
		
		// 定义 date 的数据样式
		HSSFCellStyle datestyle = workbook.createCellStyle();
		HSSFDataFormat df = workbook.createDataFormat();
		datestyle.setAlignment((short) HSSFCellStyle.ALIGN_LEFT);
		datestyle.setDataFormat(df.getFormat("yyyy-mm-dd hh:mm:ss"));

		// 定义 int 的数据样式
		HSSFCellStyle intdatestyle = workbook.createCellStyle();
		intdatestyle.setAlignment((short) HSSFCellStyle.ALIGN_LEFT);

		// 定义 float 的数据样式
		HSSFCellStyle floatdatestyle = workbook.createCellStyle();
		floatdatestyle.setAlignment((short) HSSFCellStyle.ALIGN_LEFT);
		df = workbook.createDataFormat();
		floatdatestyle.setDataFormat(df.getFormat("#.##"));

		// 定义 long 的数据样式
		HSSFCellStyle longdatestyle = workbook.createCellStyle();
		longdatestyle.setAlignment((short) HSSFCellStyle.ALIGN_LEFT);

		//title样式
		HSSFCellStyle titledatestyle = workbook.createCellStyle();
		titledatestyle.setAlignment((short) HSSFCellStyle.ALIGN_CENTER_SELECTION);
		titledatestyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		//titledatestyle.setFillBackgroundColor(HSSFColor.BLUE.index2);
		titledatestyle.setFont(celltbnamefont);
			
		// 定义列的样式
		HSSFCellStyle items_style = workbook.createCellStyle();
		items_style.setAlignment((short) HSSFCellStyle.ALIGN_CENTER); // 设置对其方式
		items_style.setFont(celltbnamefont);
		items_style.setWrapText(false); // 设置自动换行
		items_style.setFillForegroundColor(HSSFColor.ROSE.index);// 设置背景色
		items_style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		items_style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
		items_style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
		items_style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
		items_style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
		
		HSSFCellStyle row_style = workbook.createCellStyle();
		titledatestyle.setAlignment((short) HSSFCellStyle.ALIGN_CENTER_SELECTION);
		titledatestyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		
		/*
		row_style.setAlignment((short) HSSFCellStyle.ALIGN_CENTER); // 设置对其方式
		row_style.setFont(celltbnamefont);
		row_style.setWrapText(false); // 设置自动换行
		row_style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		row_style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
		row_style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
		row_style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
		row_style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
		*/
		
		
		int rowIndex = 0;
		String sheetName="兼职信息及酬劳统计";
		String head="兼职信息及酬劳统计";
		if(!Misc.isStringEmpty(partTimer.getStime())){
			head+="(时间:"+partTimer.getStime()+"-"+partTimer.getEtime()+")";
		}
		
		HSSFSheet sheet = workbook.createSheet(sheetName); // 创建工作区
		//sheet.setDefaultRowHeightInPoints(100);
		//sheet.setDefaultRowHeight((short)100);
		
		
		//合并14列 用于写 表格名称
		Region region = new Region();
	    region.setRowFrom(0);
        region.setRowFrom(0);
        region.setColumnFrom((short)0);
        region.setColumnTo((short)14);
        sheet.addMergedRegion(region);
        
        //将list 数据 打印到表格中
      	HSSFCell cell;
      	
      	//表头信息
		HSSFRow heandRow =  sheet.createRow((short) rowIndex);
		cell=heandRow.createCell(0);
		cell.setCellStyle(titledatestyle);
		cell.setCellValue(head);
		heandRow.setHeightInPoints(30);
		
		
		
		// 创建数据列名
		String titles[] = {"序号","姓名","xx名","xxID","性别","QQ","手机", "微信","微博名及粉丝","应发数量","实发数量","审核通过数","酬劳","支付宝","备注"};

		HSSFRow row =sheet.createRow((short) (++rowIndex));
		// 加入 标题
		for (int i = 0; i < titles.length; i++) {
			cell = row.createCell(i, Cell.CELL_TYPE_STRING); // 设置 列类型
			if (i ==8 || i ==11 || i==14) {
				sheet.setColumnWidth(i, 5500);
			} else {
				sheet.setColumnWidth(i, 4000);
			}
			cell.setCellValue(titles[i]);
			cell.setCellStyle(items_style);
		}
		Iterator<PartTimer> it = list.iterator();
		int index=0;
		while (it.hasNext()) {
			HSSFRow dataRow = sheet.createRow((short) (++rowIndex));
			dataRow.setHeightInPoints(20);
			dataRow.setRowStyle(row_style);
			
			PartTimer obj = it.next();
			cell = dataRow.createCell(0, Cell.CELL_TYPE_NUMERIC);
			cell.setCellStyle(longdatestyle);
			cell.setCellValue(++index);

			cell = dataRow.createCell(1, Cell.CELL_TYPE_STRING);
			cell.setCellValue(obj.getRealName());

			cell = dataRow.createCell(2, Cell.CELL_TYPE_STRING);
			cell.setCellValue(obj.getUserName());

			cell = dataRow.createCell(3, Cell.CELL_TYPE_NUMERIC);
			cell.setCellStyle(longdatestyle);
			cell.setCellValue(obj.getId());
			
			cell = dataRow.createCell(4, Cell.CELL_TYPE_STRING);
			cell.setCellValue( "1".equals(obj.getPgender()) ? "男":"女");
			
			cell = dataRow.createCell(5, Cell.CELL_TYPE_STRING);
			cell.setCellValue(obj.getPqq());
			
			cell = dataRow.createCell(6, Cell.CELL_TYPE_STRING);
			cell.setCellValue(obj.getPmobile());
			
			cell = dataRow.createCell(7, Cell.CELL_TYPE_STRING);
			cell.setCellValue(obj.getPweixin());
			
			cell = dataRow.createCell(8, Cell.CELL_TYPE_STRING);
			cell.setCellValue(obj.getPweibo());
			
			cell = dataRow.createCell(9, Cell.CELL_TYPE_STRING);
			cell.setCellValue(obj.getRequire());
			
			cell = dataRow.createCell(10, Cell.CELL_TYPE_STRING);
			cell.setCellValue(obj.getPicCount());
			
			cell = dataRow.createCell(11, Cell.CELL_TYPE_STRING);
			cell.setCellValue(obj.getPassCount());
			
			
			cell = dataRow.createCell(12, Cell.CELL_TYPE_NUMERIC);
			cell.setCellStyle(floatdatestyle);
			cell.setCellValue(obj.getRepay());
			
			cell = dataRow.createCell(13, Cell.CELL_TYPE_STRING);
			cell.setCellValue(obj.getAlipay());
			
			cell = dataRow.createCell(14, Cell.CELL_TYPE_STRING);
			cell.setCellValue(obj.getRemark());
			
		}
		//sheet.setColumnWidth(9, 2730);
		//sheet.setColumnWidth(12, 2730);
	
		
		
		/*HSSFRow dataRow = sheet.createRow((short) (++rowIndex));
		cell = dataRow.createCell(0, Cell.CELL_TYPE_STRING);
		cell.setCellStyle(intdatestyle);
		cell.setCellValue("合计:");

		cell = dataRow.createCell(1, Cell.CELL_TYPE_STRING);
		cell.setCellValue("");

		// 添加 公式
		cell = dataRow.createCell(2, Cell.CELL_TYPE_NUMERIC);
		cell.setCellStyle(longdatestyle);
		cell.setCellFormula("SUM(" + getColLetter(2)
				+ sheet.getRow(2).getCell(2).getRowIndex() + ":"
				+ getColLetter(2)
				+ sheet.getRow(sheet.getLastRowNum()).getCell(2).getRowIndex()
				+ ")");
		// 添加 公式
		cell = dataRow.createCell(3, Cell.CELL_TYPE_NUMERIC);
		cell.setCellStyle(longdatestyle);
		cell.setCellFormula("SUM(" + getColLetter(3)
				+ sheet.getRow(2).getCell(3).getRowIndex() + ":"
				+ getColLetter(3)
				+ sheet.getRow(sheet.getLastRowNum()).getCell(3).getRowIndex()
				+ ")");*/
		
		/*String workDir = ServletActionContext.getServletContext().getRealPath("/");

		String workddd = workDir.replaceAll("\\\\", "/");

		Calendar calendar = Calendar.getInstance();
		String month = calendar.get(Calendar.YEAR) + "/"
				+ (calendar.get(Calendar.MONTH) + 1);
		String filePath = "newsxls/adxls/" + month + "/";
		File f = new File(workDir + filePath);
		if (!f.isDirectory()) {
			f.mkdirs();
		}

		String fileNameCode = java.util.UUID.randomUUID().toString();
		String completeFilePath = workddd + filePath + fileNameCode + ".xls";
		FileOutputStream fileOut = new FileOutputStream(completeFilePath);
		workbook.write(fileOut);
		fileOut.flush();
		fileOut.close();*/
		
		return workbook;
	}
分享到:
评论

相关推荐

    getOutputStream() has already been called for this response 错误解决

    在Java Web开发中,"getOutputStream() has already been called for this response" 是一个常见的错误,通常出现在使用Servlet或JSP时。这个错误意味着在HTTP响应中,`getOutputStream()`已经被调用,然后尝试再次...

    tomcat6下jsp出现getOutputStream() has already been called for this response异常的原因和解决方法

    1.在tomcat6.0下jsp出现getOutputStream() has already been called for this response异常的原因和解决方法  在tomcat6.0下jsp中出现此错误一般都是在jsp中使用了输出流(如输出图片验证码,文件下载等),没有...

    验证码出现getOutputStream()问题解决

    验证码出现getOutputStream() has already been called for this response错误解决

    java.lang.IllegalStateException: getOutputStream() has already解决办法

    纠结了半天的 java.lang.IllegalStateException: getOutputStream() has already。这个问题困扰了半天,在网上查阅了大量资料 出这个错误一般就是下面2个.....

    JSP彩色验证码

    解决了getOutputStream() has already been called for this response. 并将产生验证码的逻辑从JSP页面中分离出来,单独写了一个类 便于重用。

    Cannot forward after response has been committed

    通过仔细审查代码、优化逻辑和正确处理异常,可以有效地解决"Cannot forward after response has been committed"的问题。 关于提供的"filterTest"文件,可能是用于测试过滤器功能的示例代码。分析和理解这段代码...

    handleStream ServletOutputStream out = response.getOutputStream(); InputStream i

    ServletOutputStream out = response.getOutputStream(); out.write("&lt;html&gt;&lt;body&gt;Hello, World!&lt;/body&gt;&lt;/html&gt;".getBytes()); out.flush(); out.close(); ``` 描述中的"InputStream i" 提到了输入流`InputStream`...

    java.lang.IllegalStateException: OutputStream already obtain

    标题 "java.lang.IllegalStateException: OutputStream already obtain" 涉及到的是Java编程中的一个常见错误,特别是当处理I/O流时。这个异常通常在尝试获取已经存在的OutputStream实例时抛出,表明该输出流已经被...

    response设置的实例源码

    本篇将深入探讨`response`设置的实例源码,以及如何在Servlet中应用这些设置。 一、Response对象的基本介绍 `HttpServletResponse`接口是`ServletResponse`接口的子接口,它扩展了通用的响应功能,以适应HTTP协议的...

    response中文乱码解决的代码

    3. 使用`FileInputStream`读取文件内容,并通过`response.getOutputStream().write()`将内容写入响应流。 通过以上方法,我们可以在处理中文文件名的文件下载时,有效避免乱码问题,确保用户能够正确下载并识别文件...

    Response-Headers详解

    try (OutputStream out = response.getOutputStream()) { // 使用Apache POI或其他库生成Excel内容并写入out流 } ``` #### 五、动态生成JPEG图像 如果需要动态生成并发送JPEG格式的图像,也需要设置正确的响应...

    servlet2.4doc

    Returns a boolean indicating whether the named response header has already been set. contextDestroyed(ServletContextEvent) - Method in interface javax.servlet.ServletContextListener Notification ...

    java response 下载文件方法

    OutputStream ou = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); // 设置响应类型为二进制流 // 写入响应流并关闭 ou.write(buffer); ou....

    HttpServletRequest-response方法总结

    2. getOutputStream():从Servlet中可以通过getOutputStream方法取得ServletOutputStream对象,既可以输出字符数据,也可以输出MIME格式的二进制数据。 3. setContentType():在响应中可以表明内容格式和长度。 4. ...

    response生成图片验证

    这里使用了Servlet的`HttpServletResponse`对象,调用其`setContentType`方法设置响应的MIME类型为`image/jpeg`或`image/png`,然后使用`getOutputStream`获取输出流,并调用`ImageIO.write`方法将图片写入。...

    response jsp 中的重要知识点

    在Java Web开发中,`response.jsp`通常是指服务器端的响应页面,主要涉及Servlet和JSP(JavaServer Pages)技术。`response`对象是Servlet API中的一个关键组件,全称为`HttpServletResponse`,它用于构建并发送回...

    JSP内置对象request和response.doc

    JSP内置对象request和response详解 JSP内置对象request和response是JSP开发中两个非常重要的对象,它们分别用于处理客户端请求和响应信息。在本文档中,我们将详细介绍request和response对象的功能和使用方法。 ...

    Request&Response-授课

    ServletOutputStream sos = response.getOutputStream(); //解决中文乱码问题 response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); sos.write(str.getBytes()); } ...

    JAVAEE中Servlet实例Response与Request对象方法调用范例

    3. `getOutputStream()`:返回ServletOutputStream,用于写入二进制数据到响应体,如文件下载。 4. `getWriter()`:返回PrintWriter,用于写入文本数据到响应体,如HTML、JSON等。 在实际应用中,我们通常会创建一...

Global site tag (gtag.js) - Google Analytics