아놔..별 귀찮을 걸 다 시키네..
jrxml 파일을 컴파일한후..PDF와 XLS를 다운받게 만들어주는 서블릿...
1. ReportPdfServlet.java
Package test.report;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import db.DBConnection;
/**
* jasper 리포트를 이용 pdf파일을 생성하는 서블릿
* @author aircook
* @since 2007-07-05
*/
public class ReportPdfServlet extends HttpServlet {
private static final long serialVersionUID = -6185265574999158988L;
private final Log logger = LogFactory.getLog(getClass());
private final String reportDir = "reports";
@Override
public void init() throws ServletException {
if (logger.isDebugEnabled()) {
logger.info("init() 시작...");
}
ServletContext context = this.getServletConfig().getServletContext();
// 컴파일러 위치..
System.setProperty("jasper.reports.compile.class.path", context
.getRealPath("/WEB-INF/lib/jasperreports-1.3.4.jar")
+ System.getProperty("path.separator") + context.getRealPath("/WEB-INF/classes/"));
// jasper 컴파일을 위한 임시디렉토리 지정..
System.setProperty("jasper.reports.compile.temp", context.getRealPath("/"+reportDir+"/"));
}
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
if (logger.isDebugEnabled()) {
logger.info("service() 시작...");
}
ServletContext context = this.getServletConfig().getServletContext();
Connection con = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
// http 파라미터 받음..
String reportName = request.getParameter("reportName");
String reportTitle = request.getParameter("reportTitle");
String param1 = request.getParameter("param1");
if (logger.isDebugEnabled()) {
logger.debug("reportName : "+reportName);
logger.debug("reportTitle : "+reportTitle);
logger.debug("param1 : "+param1);
}
// 임시로 파일명 지정 삭제할것..
//reportName = "test1";
// jasper로 넘기는 파리미터
Map parameters = new HashMap();
parameters.put("reportTitle", reportTitle);
// 디비 연결
DBConnection connection = new DBConnection();
con = connection.getConnection();
// compile --------------------------------------------------------------------------------------------------------------------------------------
// 컴파일 결과 파일
File compiledFile = new File(context.getRealPath("/"+reportDir+"/" + reportName + ".jasper"));
if (logger.isDebugEnabled()) {
logger.debug("compiledFile : " + context.getRealPath("/"+reportDir+"/" + reportName + ".jasper"));
logger.debug("reportFile.exists() : " + compiledFile.exists());
}
if (!compiledFile.exists()) {
JasperCompileManager.compileReportToFile(context.getRealPath("/"+reportDir+"/" + reportName + ".jrxml"));
}
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(compiledFile.getPath());
// fill ------------------------------------------------------------------------------------------------------------------------------------------
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, con);
// PDF
JRPdfExporter exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
exporter.exportReport();
// export --------------------------------------------------------------------------------------------------------------------------------------
byte[] bytes = baos.toByteArray();
if (bytes != null && bytes.length > 0) {
response.setContentType("application/pdf");
response.setContentLength(bytes.length);
response.setHeader("Content-disposition","attachment; filename=\""+reportTitle+".pdf\"");
ServletOutputStream ouputStream = response.getOutputStream();
try {
ouputStream.write(bytes, 0, bytes.length);
ouputStream.flush();
}finally {
if (ouputStream != null) {
try {
ouputStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
} // fianlly
} // if
}
catch (Exception e) {
e.printStackTrace();
}
}
}
2. ReportXlsServlet.java
package test.report;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.util.JRLoader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import db.DBConnection;
/**
* jasper 리포트를 이용 엑셀파일을 생성하는 서블릿
* @author aircook
* @since 2007-07-05
*/
public class ReportXlsServlet extends HttpServlet {
private static final long serialVersionUID = -6185265574999158988L;
private final Log logger = LogFactory.getLog(getClass());
private final String reportDir = "reports";
@Override
public void init() throws ServletException {
if (logger.isDebugEnabled()) {
logger.info("init() 시작...");
}
ServletContext context = this.getServletConfig().getServletContext();
// 컴파일러 위치..
System.setProperty("jasper.reports.compile.class.path", context
.getRealPath("/WEB-INF/lib/jasperreports-1.3.4.jar")
+ System.getProperty("path.separator") + context.getRealPath("/WEB-INF/classes/"));
// jasper 컴파일을 위한 임시디렉토리 지정..
System.setProperty("jasper.reports.compile.temp", context.getRealPath("/"+reportDir+"/"));
}
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
if (logger.isDebugEnabled()) {
logger.info("service() 시작...");
}
ServletContext context = this.getServletConfig().getServletContext();
Connection con = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
// http 파라미터 받음..
String reportName = request.getParameter("reportName");
String reportTitle = request.getParameter("reportTitle");
String param1 = request.getParameter("param1");
if (logger.isDebugEnabled()) {
logger.debug("reportName : "+reportName);
logger.debug("reportTitle : "+reportTitle);
logger.debug("param1 : "+param1);
}
// 임시로 파일명 지정 삭제할것..
//reportName = "test1";
// jasper로 넘기는 파리미터
Map parameters = new HashMap();
parameters.put("reportTitle", reportTitle);
parameters.put("param1", param1);
// 디비 연결
DBConnection connection = new DBConnection();
con = connection.getConnection();
// compile --------------------------------------------------------------------------------------------------------------------------------------
// 컴파일 결과 파일
File compiledFile = new File(context.getRealPath("/"+reportDir+"/" + reportName + ".jasper"));
if (logger.isDebugEnabled()) {
logger.debug("compiledFile : " + context.getRealPath("/"+reportDir+"/" + reportName + ".jasper"));
logger.debug("reportFile.exists() : " + compiledFile.exists());
}
if (!compiledFile.exists()) {
JasperCompileManager.compileReportToFile(context.getRealPath("/"+reportDir+"/" + reportName + ".jrxml"));
}
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(compiledFile.getPath());
// fill ------------------------------------------------------------------------------------------------------------------------------------------
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, con);
// XLS
JRXlsExporter exporter = new JRXlsExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
exporter.exportReport();
// export --------------------------------------------------------------------------------------------------------------------------------------
byte[] bytes = baos.toByteArray();
if (bytes != null && bytes.length > 0) {
response.setContentType("application/vnd.ms-excel");
response.setContentLength(bytes.length);
response.setHeader("Content-disposition","attachment; filename=\""+reportTitle+".xls\"");
ServletOutputStream ouputStream = response.getOutputStream();
try {
ouputStream.write(bytes, 0, bytes.length);
ouputStream.flush();
}finally {
if (ouputStream != null) {
try {
ouputStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
} // fianlly
} // if
}
catch (Exception e) {
e.printStackTrace();
}
}
}
3. test1.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ko" xml:lang="ko">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>test1</title>
<script language="javascript">
function doTest(){
if (document.form1.exportType.value == "PDF"){
var actionName="servlet/ReportPdfServlet";
}else{
var actionName="servlet/ReportXlsServlet";
}
document.form1.action="<%=request.getContextPath()%>/"+actionName;
document.form1.submit();
}
</script>
</head>
<body>
<div id="header">
TEST1
</div>
<div id="submenu">
<form name="form1" method="post">
<table border=1 cellspacing="2" cellpadding="0" width="500">
<tr>
<td>파일종류</td>
<td>
<select name="exportType">
<option value="PDF">PDF</option>
<option value="XLS">XLS</option>
</select>
</td>
</tr>
<tr>
<td>jasper 파일명</td>
<td><input type="text" name="reportName" value="test1" /></td>
</tr>
<tr>
<td>파라미터 1</td>
<td><input type="text" name="reportTitle" value="reportTitle" /></td>
</tr>
<tr>
<td>파라미터 2</td>
<td><input type="text" name="param1" value="param1"/></td>
</tr>
<tr>
<td colspan="2"><input type="button" value="doTest" onClick="doTest()"></td>
</tr>
</table>
</form>
</div>
<div id="footer">
by aircook...
</div>
</body>
</html>
'java' 카테고리의 다른 글
Jakarta String Tag Library (4) | 2007.12.13 |
---|---|
현재 프로젝트의 자바 라이브러리 정리.. (0) | 2007.09.14 |
JSP 표현식 언어(EL) 종합 (0) | 2007.06.19 |
oracle8i/jdbc/tomcat (0) | 2004.09.15 |
mssql/jdbc/tomcat (0) | 2004.09.14 |