问题描述
Servlet代码privateFileAttachServicefileAttachService=(FileAttachService)AppUtil.getBean("fileAttachService");privateLoglogger=LogFactory.getLog(FilePreviewServlet.class);protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{StringfileId=req.getParameter("fileId");req.setCharacterEncoding("UTF-8");resp.setCharacterEncoding("UTF-8");if(StringUtils.isNotEmpty(fileId)){FileAttachfileAttach=(FileAttach)this.fileAttachService.get(newLong(fileId));Stringext=fileAttach.getExt();if((ext.toLowerCase().endsWith("doc"))||(ext.toLowerCase().endsWith("docx"))){resp.setContentType("application/msword");}elseif((ext.toLowerCase().endsWith("xls"))||(ext.toLowerCase().endsWith("csv"))){resp.setContentType("application/ms-excel");}elseif(ext.toLowerCase().endsWith("pdf")){resp.setContentType("application/pdf");}elseif(ext.toLowerCase().endsWith("txt")){resp.setContentType("text/plain");}elseif(ext.toLowerCase().endsWith("jpg")){resp.setContentType("image/jpg");}elseif(ext.toLowerCase().endsWith("jpeg")){resp.setContentType("image/jpeg");}elseif(ext.toLowerCase().endsWith("gif")){resp.setContentType("image/gif");}elseif(ext.toLowerCase().endsWith("png")){resp.setContentType("image/png");}elseif(ext.toLowerCase().endsWith("bmp")){resp.setContentType("image/bmp");}else{return;}ServletOutputStreamout=null;try{FileInputStreamfileIn=newFileInputStream(getServletContext().getRealPath("/")+"/attachFiles/"+fileAttach.getFilePath());Stringpath=getServletContext().getRealPath("/")+"/attachFiles/"+fileAttach.getFilePath();this.logger.info("loadfilePath:"+path);System.out.println("loadfilepath"+path);resp.setHeader("Content-Disposition","inline;filename="+URLEncoder.encode(fileAttach.getFileName(),"UTF-8"));out=resp.getOutputStream();byte[]buff=newbyte[1024];intleng=fileIn.read(buff);while(leng>0){out.write(buff,0,leng);leng=fileIn.read(buff);}}catch(Exceptionex){ex.printStackTrace();if(out!=null){try{out.flush();}catch(IOExceptione){e.printStackTrace();}try{out.close();}catch(IOExceptione){e.printStackTrace();}}}finally{if(out!=null){try{out.flush();}catch(IOExceptione){e.printStackTrace();}try{out.close();}catch(IOExceptione){e.printStackTrace();}}}}}JSP代码:request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");response.setCharacterEncoding("utf-8");//查询条件1、条件2Stringcondition1=null;//Stringcondition2=null;//报表类型StringreportType=null;Stringstrid=request.getParameter("reportId");Longid=newLong("0");if(StringUtils.isNotEmpty(strid)){id=Long.parseLong(strid);}ReportParamServicereportParamService=(ReportParamService)AppUtil.getBean("reportParamService");List<ReportParam>plist=reportParamService.findByRepTemp(id);MapvalueMap=request.getParameterMap();MaptypeMap=newHashMap();Mapparameters=newHashMap();SimpleDateFormatformat=newSimpleDateFormat();for(ReportParamp:plist){typeMap.put(p.getParamKey(),p.getParamType());}Iteratorit=valueMap.entrySet().iterator();while(it.hasNext()){Map.Entryentry=(Map.Entry)it.next();Stringkey=(String)entry.getKey();String[]values=(String[])entry.getValue();Stringvalue=URLDecoder.decode(values[0],"UTF-8");ObjectparamType=typeMap.get(key);if(paramType!=null){StringparamTypeStr=paramType.toString();if(paramTypeStr.equals("datefield")){format.applyPattern("yyyy-MM-dd");DatedateValue=format.parse(value);parameters.put(key,newjava.sql.Time(dateValue.getTime()));}elseif(paramTypeStr.equals("datetimefield")){format.applyPattern("yyyy-MM-ddHH:mm:ss");DatedateValue=format.parse(value);parameters.put(key,newjava.sql.Time(dateValue.getTime()));}elseif(paramTypeStr.equals("numberfield")){if(value!=null&&!value.equals("")){DoubledoubleValue=Double.parseDouble(value);parameters.put(key,doubleValue);}else{parameters.put(key,"%");}}else{if(value!=null&&!value.equals("")){parameters.put(key,value);}else{parameters.put(key,"%");}}}else{parameters.put(key,value);}}//根据页面传来的reportId查找上传后的报表模版路径StringreportPath="";StringreportName="";ReportTemplateServicereportTemplateService=(ReportTemplateService)AppUtil.getBean("reportTemplateService");ReportTemplatereportTemplate=reportTemplateService.get(id);reportPath=reportTemplate.getReportLocation();reportName=reportTemplate.getTitle();//Mapparameters=newReportFilter((HttpServletRequest)request).getVariables();//现在报表模版只设置了一个参数,这里也暂时只接受一个参数//condition2=request.getParameter("condition2");//if(condition2==null){//parameters.put("noticeId",0);//}else{//parameters.put("noticeId",condition2);//}/*要是报表中用到了图片的话,在这里设置图片路径参数为相对路径,把图片放在项目中第一个参数是在iReport中设置的图片参数名字,第二个参数是图片所在的项目目录*///parameters.put("REPORT_LOGO_DIR","report\jasper\");reportType=request.getParameter("reportType");StringrootPath=application.getRealPath("/attachFiles");//报表模版附件上传后的根目录try{DataSourcedataSource=(DataSource)AppUtil.getBean("dataSource");Connectionconn=dataSource.getConnection();FilefullPath=newFile(rootPath+"/"+reportPath);//上传后的报表模板的全路径//将解析完的参数传入报表模板中并生成报表//如果接收到的参数为pdf类型的话,则生成pdf的报表System.out.println(fullPath.getPath()+","+parameters);if("pdf".equals(reportType)){byte[]bytes=JasperRunManager.runReportToPdf(fullPath.getPath(),parameters,conn);//设置报表生成类型为PDFresponse.setContentType("application/pdf;charset=utf-8");request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");response.setContentLength(bytes.length);reportName=reportName+".pdf";response.setHeader("Content-Disposition","attachment;filename="+newString(reportName.getBytes("gb2312"),"ISO8859-1"));ServletOutputStreamouputStream=response.getOutputStream();ouputStream.write(bytes,0,bytes.length);ouputStream.flush();ouputStream.close();conn.close();out.clear();out=pageContext.pushBody();}elseif("xls".equals(reportType)){//如果接受到的参数为xls(excel类型)的话,则生成xls类型的报表JRXlsExporterexporter=newJRXlsExporter();ByteArrayOutputStreamoStream=newByteArrayOutputStream();JasperPrintjasperPrint=JasperFillManager.fillReport(fullPath.getPath(),parameters,conn);exporter.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint);exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,oStream);exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,Boolean.TRUE);exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,Boolean.FALSE);exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,Boolean.FALSE);exporter.exportReport();byte[]bytes=oStream.toByteArray();//设置报表生成类型为excelresponse.setContentType("application/vnd.ms-excel");request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");response.setContentLength(bytes.length);reportName=reportName+".xls";response.setHeader("Content-Disposition","attachment;filename="+newString(reportName.getBytes("gb2312"),"ISO8859-1"));ServletOutputStreamouputStream=response.getOutputStream();ouputStream.write(bytes,0,bytes.length);ouputStream.flush();ouputStream.close();conn.close();out.clear();out=pageContext.pushBody();}else{System.out.println("jspparameters="+parameters);//否则生成html类型的报表JRHtmlExporterexporter=newJRHtmlExporter();ByteArrayOutputStreamoStream=newByteArrayOutputStream();System.out.println("fullPath.getPath()="+fullPath.getPath());System.out.println("jspparameters="+parameters);System.out.println("conn="+conn);JasperPrintjasperPrint=JasperFillManager.fillReport(fullPath.getPath(),parameters,conn);//这里也是解决HTML报表图片不显示的session.setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,jasperPrint);exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,Boolean.FALSE);//下面这一句是解决HTML报表图片不显示的问题,注意URI得写对,这里URI是指jasper文件所在的目录exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,"jasper?"+"time="+(newDate()).toString()+"&image=");exporter.setParameter(JRHtmlExporterParameter.JASPER_PRINT,jasperPrint);exporter.setParameter(JRHtmlExporterParameter.CHARACTER_ENCODING,"utf-8");exporter.setParameter(JRHtmlExporterParameter.OUTPUT_STREAM,oStream);exporter.exportReport();byte[]bytes=oStream.toByteArray();//设置报表生成类型的htmlresponse.setContentType("text/html;charset=utf-8");request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");response.setContentLength(bytes.length);ServletOutputStreamouputStream=response.getOutputStream();ouputStream.write(bytes,0,bytes.length);ouputStream.flush();ouputStream.close();conn.close();out.clear();out=pageContext.pushBody();}}catch(Exceptionex){ex.printStackTrace();}每次执行展示操作JasperPrintjasperPrint=JasperFillManager.fillReport(fullPath.getPath(),parameters,conn);这个地方就报错