新建一 web 项目 Test2。将 iReport 目录 lib 下的所有 jar 包导入。在 servlet 程序中把从数据库得到的数据传入 *.jrxml 文件得到 *.jrprint 文件(这才是我们想要的东西),并把这个对象写入 Stream流,以返还给请求客户端。源码:
- package com.defonds.test;
- import java.io.File;
- import java.io.IOException;
- import java.io.ObjectOutputStream;
- import javax.servlet.RequestDispatcher;
- import javax.servlet.ServletException;
- import javax.servlet.ServletOutputStream;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.Calendar;
- import java.util.HashMap;
- import java.util.Map;
- import net.sf.jasperreports.engine.JRResultSetDataSource;
- import net.sf.jasperreports.engine.JasperCompileManager;
- import net.sf.jasperreports.engine.JasperExportManager;
- import net.sf.jasperreports.engine.JasperFillManager;
- import net.sf.jasperreports.engine.JasperPrint;
- import net.sf.jasperreports.engine.JasperReport;
- import net.sf.jasperreports.engine.JasperRunManager;
- /**
- * 建立数据库链接
- * 由 sql 语法取出资料,准备好传入的 parameters
- * 将 parameters 及取出的资料传入 Jasper 中。会由 .jasper 文档生出 .jrprint 文档
- * 再由 .jrprint 文档生出 .pdf 目的文档给调用页面下载
- * @author Defonds
- *
- */
- public class TestServlet3 extends HttpServlet {
- private static final String CONTENTTYPE = "application/octet-stream";
- /**
- * Constructor of the object.
- */
- public TestServlet3() {
- super();
- }
- /**
- * Destruction of the servlet. <br>
- */
- public void destroy() {
- super.destroy(); // Just puts "destroy" string in log
- // Put your code here
- }
- /**
- * The doGet method of the servlet. <br>
- *
- * This method is called when a form has its tag value method equals to get.
- *
- * @param request the request send by the client to the server
- * @param response the response send by the server to the client
- * @throws ServletException if an error occurred
- * @throws IOException if an error occurred
- */
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String fileName = "";
- String sql = "";
- Map parameters = new HashMap();
- //parameters.put("rptToday", strDate);//传入的 prameters 引数
- sql = "select * from tab_channel_car_basic t";
- Connection conn = this.createConnection();//建立连接
- try {
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery(sql);
- response.setContentType(CONTENTTYPE);
- ServletOutputStream ouputStream = response.getOutputStream();
- fileName="D://iReport//iReport-0.4.0//Work//carBasic3.jrxml";
- JasperReport jrt = JasperCompileManager.compileReport(fileName);//编译报表格式
- JasperPrint jpt = JasperFillManager.fillReport(jrt, parameters, new JRResultSetDataSource(rs));//匹配数据源,生成JasperPrint
- ObjectOutputStream oos = new ObjectOutputStream(ouputStream);
- oos.writeObject(jpt);
- oos.flush();
- oos.close();
- }catch(Exception e) {
- System.out.println("Error:" + e.toString());
- e.printStackTrace();
- }finally {
- CloseConnect(conn);
- conn = null;
- }
- }
- /**
- * 建立连接方法
- * @return Connection
- */
- public Connection createConnection() {
- Connection conn;
- try {
- String driver = "oracle.jdbc.driver.OracleDriver";
- String url = "jdbc:oracle:thin:@localhost:1521:CUC";
- Class.forName(driver);
- conn = DriverManager.getConnection(url,"sybj","sybj");
- conn.setAutoCommit(false);
- return conn;
- }catch(SQLException e1) {
- System.out.println("建立连接错误 = " + e1.toString());
- e1.printStackTrace();
- }catch(ClassNotFoundException e2) {
- System.out.println("建立连接错误 = " + e2.toString());
- e2.printStackTrace();
- }
- return null;
- }
- /**
- * 关闭连接方法
- * @param conn
- */
- public void CloseConnect(Connection conn) {
- try {
- conn.commit();
- conn.setAutoCommit(true);
- conn.close();
- }catch(Exception e) {
- System.out.println("关闭连接错误 = " + e.toString());
- }
- }
- }
PS:这里,关于 carBasic3.jrxml 文件的提取,笔者采用的是物理路径,读者可以把 *.jrxml 文件放到项目根目录下,然后采用其他方式提取。
如果输入http://localhost:9999/Test2/testServlet3 就弹出来一个下载窗口,证明这个 servlet 已经 ok(笔者 tomcat 端口号设置的是 9999,在 Test2 项目中进行测试)。
7、applet 请求服务器 servlet 得到 JasperPrint 对象并打印。源码:
- package com.defonds.test;
- import java.applet.Applet;
- import java.io.PrintWriter;
- import java.io.StringWriter;
- import java.net.URL;
- import javax.swing.JOptionPane;
- import net.sf.jasperreports.engine.JasperPrint;
- import net.sf.jasperreports.engine.JasperPrintManager;
- import net.sf.jasperreports.engine.util.JRLoader;
- public class JRPrinterApplet extends javax.swing.JApplet
- {
- /**
- *
- */
- private URL url = null;
- private JasperPrint jasperPrint = null;
- /** Creates new form AppletViewer */
- public JRPrinterApplet()
- {
- }
- /**
- *
- */
- public void init()
- {
- // String strUrl = getParameter("REPORT_URL");
- String strUrl = "http://localhost:9999/Test2/testServlet3";
- if (strUrl != null)
- {
- try
- {
- //url = new URL(getCodeBase(), strUrl);
- URL urll = new URL("http://localhost:9999/Test2/testServlet3");
- url = urll;
- System.out.println("url="+urll);
- }
- catch (Exception e)
- {
- StringWriter swriter = new StringWriter();
- PrintWriter pwriter = new PrintWriter(swriter);
- e.printStackTrace(pwriter);
- JOptionPane.showMessageDialog(this, swriter.toString());
- }
- }
- else
- {
- JOptionPane.showMessageDialog(this, "init():Source URL not specified");
- }
- }
- public void start() {
- if (url != null)
- {
- if (jasperPrint == null)
- {
- try
- {
- System.out.println("进入start方法,即将下载pdf文件");
- jasperPrint = (JasperPrint)JRLoader.loadObject(url);
- System.out.println("进入start方法,下载pdf文件完毕");
- }
- catch (Exception e)
- {
- StringWriter swriter = new StringWriter();
- PrintWriter pwriter = new PrintWriter(swriter);
- e.printStackTrace(pwriter);
- JOptionPane.showMessageDialog(this, swriter.toString());
- }
- }
- if (jasperPrint != null)
- {
- final JasperPrint print = jasperPrint;
- Thread thread = new Thread
- (
- new Runnable()
- {
- public void run()
- {
- try
- {
- System.out.println("进入start方法,即将打印pdf文件");
- JasperPrintManager.printReport(print, true);
- }
- catch (Exception e)
- {
- StringWriter swriter = new StringWriter();
- PrintWriter pwriter = new PrintWriter(swriter);
- e.printStackTrace(pwriter);
- JOptionPane.showMessageDialog(null, swriter.toString());
- }
- }
- }
- );
- thread.start();
- }
- else
- {
- JOptionPane.showMessageDialog(this, "Empty report.");
- }
- }
- else
- {
- JOptionPane.showMessageDialog(this, "start():Source URL not specified");
- }
- }
- }
右键单击 JRPrinterApplet.java,选择 “Run as Java Applet”,弹出打印对话框,确认后打印机正常打印,证明 applet 已经编写成功。
8、jsp 页面嵌入 applet源码:
- <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
- <%
- 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 'index.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" mce_href="styles.css">
- -->
- </head>
- <mce:script language="javascript"><!--
- function openApp()
- {
- var url = "/JRPrintServlet";
- document.write('<APPLET ID="JrPrt" CODE="com.defonds.test.JRPrinterApplet.class" CODEBASE = "./" ARCHIVE = "reportprint.jar" WIDTH = "0" HEIGHT = "0">');
- document.write('<PARAM NAME = "type" VALUE="application/x-java-applet;version=1.2.2">');
- document.write('<PARAM NAME = "scriptable" VALUE="false">');
- document.write('<PARAM NAME = "REPORT_URL" VALUE ="'+url+'">');
- document.write('</APPLET>');
- }
- // --></mce:script>
- <body bgcolor="#FFFFFF">
- <input type="button" value="测试打印" onclick="openApp();">
- </body>
- </html>