Applet+客户端打印+jasperreport+报表

新建一 web 项目 Test2。将 iReport 目录 lib 下的所有 jar 包导入。在 servlet 程序中把从数据库得到的数据传入 *.jrxml 文件得到 *.jrprint 文件(这才是我们想要的东西),并把这个对象写入 Stream流,以返还给请求客户端。源码:

 

view plain print ?
  1. package com.defonds.test;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.io.ObjectOutputStream;  
  6.   
  7. import javax.servlet.RequestDispatcher;  
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.ServletOutputStream;  
  10. import javax.servlet.http.HttpServlet;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13. import java.sql.Connection;  
  14. import java.sql.DriverManager;  
  15. import java.sql.ResultSet;  
  16. import java.sql.SQLException;  
  17. import java.sql.Statement;  
  18. import java.util.Calendar;  
  19. import java.util.HashMap;  
  20. import java.util.Map;  
  21.   
  22. import net.sf.jasperreports.engine.JRResultSetDataSource;  
  23. import net.sf.jasperreports.engine.JasperCompileManager;  
  24. import net.sf.jasperreports.engine.JasperExportManager;  
  25. import net.sf.jasperreports.engine.JasperFillManager;  
  26. import net.sf.jasperreports.engine.JasperPrint;  
  27. import net.sf.jasperreports.engine.JasperReport;  
  28. import net.sf.jasperreports.engine.JasperRunManager;  
  29.   
  30. /** 
  31.  * 建立数据库链接 
  32.  * 由 sql 语法取出资料,准备好传入的 parameters 
  33.  * 将 parameters 及取出的资料传入 Jasper 中。会由 .jasper 文档生出 .jrprint 文档 
  34.  * 再由 .jrprint 文档生出 .pdf 目的文档给调用页面下载 
  35.  * @author Defonds 
  36.  * 
  37.  */  
  38. public class TestServlet3 extends HttpServlet {  
  39.    
  40.  private static final String CONTENTTYPE = "application/octet-stream";   
  41.   
  42.     /** 
  43.      * Constructor of the object. 
  44.      */  
  45.     public TestServlet3() {  
  46.         super();  
  47.     }  
  48.   
  49.     /** 
  50.      * Destruction of the servlet. 
     
  51.      */  
  52.     public void destroy() {  
  53.         super.destroy(); // Just puts "destroy" string in log  
  54.         // Put your code here  
  55.     }  
  56.   
  57.     /** 
  58.      * The doGet method of the servlet. 
     
  59.      * 
  60.      * This method is called when a form has its tag value method equals to get. 
  61.      *  
  62.      * @param request the request send by the client to the server 
  63.      * @param response the response send by the server to the client 
  64.      * @throws ServletException if an error occurred 
  65.      * @throws IOException if an error occurred 
  66.      */  
  67.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  68.             throws ServletException, IOException {  
  69.      String fileName = "";  
  70.      String sql = "";  
  71.      Map parameters = new HashMap();  
  72.      //parameters.put("rptToday", strDate);//传入的 prameters 引数  
  73.      sql = "select * from tab_channel_car_basic t";  
  74.        
  75.      Connection conn = this.createConnection();//建立连接  
  76.      try {  
  77.       Statement stmt = conn.createStatement();  
  78.       ResultSet rs = stmt.executeQuery(sql);  
  79.       response.setContentType(CONTENTTYPE);    
  80.       ServletOutputStream ouputStream = response.getOutputStream();    
  81.       fileName="D://iReport//iReport-0.4.0//Work//carBasic3.jrxml";  
  82.       JasperReport jrt = JasperCompileManager.compileReport(fileName);//编译报表格式   
  83.       JasperPrint jpt = JasperFillManager.fillReport(jrt, parameters, new JRResultSetDataSource(rs));//匹配数据源,生成JasperPrint  
  84.       ObjectOutputStream oos = new ObjectOutputStream(ouputStream);   
  85.       oos.writeObject(jpt);      
  86.             oos.flush();      
  87.             oos.close();   
  88.   
  89.   
  90.      }catch(Exception e) {  
  91.       System.out.println("Error:" + e.toString());  
  92.       e.printStackTrace();  
  93.      }finally {  
  94.       CloseConnect(conn);  
  95.       conn = null;  
  96.      }  
  97.        
  98.     }  
  99.        
  100.     /** 
  101.      * 建立连接方法 
  102.      * @return Connection 
  103.      */  
  104.      public Connection createConnection() {  
  105.       Connection conn;  
  106.       try {  
  107.        String driver = "oracle.jdbc.driver.OracleDriver";  
  108.        String url = "jdbc:oracle:thin:@localhost:1521:CUC";  
  109.        Class.forName(driver);  
  110.        conn = DriverManager.getConnection(url,"sybj","sybj");  
  111.        conn.setAutoCommit(false);  
  112.        return conn;  
  113.       }catch(SQLException e1) {  
  114.        System.out.println("建立连接错误 = " + e1.toString());  
  115.        e1.printStackTrace();  
  116.       }catch(ClassNotFoundException e2) {  
  117.        System.out.println("建立连接错误 = " + e2.toString());  
  118.        e2.printStackTrace();  
  119.       }  
  120.       return null;  
  121.      }  
  122.        
  123.     /** 
  124.      * 关闭连接方法 
  125.      * @param conn 
  126.      */   
  127.     public void CloseConnect(Connection conn) {  
  128.      try {  
  129.       conn.commit();  
  130.       conn.setAutoCommit(true);  
  131.       conn.close();  
  132.      }catch(Exception e) {  
  133.       System.out.println("关闭连接错误 = " + e.toString());  
  134.      }  
  135.     }  
  136.       
  137.   
  138. }  

 

PS:这里,关于 carBasic3.jrxml 文件的提取,笔者采用的是物理路径,读者可以把 *.jrxml 文件放到项目根目录下,然后采用其他方式提取。
如果输入
http://localhost:9999/Test2/testServlet3 就弹出来一个下载窗口,证明这个 servlet 已经 ok(笔者 tomcat 端口号设置的是 9999,在 Test2 项目中进行测试)。
7、applet 请求服务器 servlet 得到 JasperPrint 对象并打印。源码:

 

view plain print ?
  1. package com.defonds.test;  
  2.   
  3. import java.applet.Applet;  
  4. import java.io.PrintWriter;  
  5. import java.io.StringWriter;  
  6. import java.net.URL;  
  7.   
  8. import javax.swing.JOptionPane;  
  9.   
  10. import net.sf.jasperreports.engine.JasperPrint;  
  11. import net.sf.jasperreports.engine.JasperPrintManager;  
  12. import net.sf.jasperreports.engine.util.JRLoader;  
  13.   
  14. public class JRPrinterApplet extends javax.swing.JApplet      
  15. {      
  16.      
  17.      
  18.     /**    
  19.      *    
  20.      */     
  21.     private URL url = null;      
  22.     private JasperPrint jasperPrint = null;      
  23.      
  24.      
  25.     /** Creates new form AppletViewer */     
  26.     public JRPrinterApplet()      
  27.     {      
  28.               
  29.     }      
  30.      
  31.      
  32.     /**    
  33.     *    
  34.     */     
  35.     public void init()      
  36.     {      
  37. //        String strUrl = getParameter("REPORT_URL");      
  38.      String strUrl = "http://localhost:9999/Test2/testServlet3";  
  39.         if (strUrl != null)      
  40.         {      
  41.             try     
  42.             {      
  43.                 //url = new URL(getCodeBase(), strUrl);      
  44.              URL urll = new URL("http://localhost:9999/Test2/testServlet3");  
  45.              url = urll;  
  46.        System.out.println("url="+urll);  
  47.             }      
  48.             catch (Exception e)      
  49.             {      
  50.                 StringWriter swriter = new StringWriter();      
  51.                 PrintWriter pwriter = new PrintWriter(swriter);      
  52.                 e.printStackTrace(pwriter);      
  53.                 JOptionPane.showMessageDialog(this, swriter.toString());      
  54.             }      
  55.         }      
  56.         else     
  57.         {      
  58.         JOptionPane.showMessageDialog(this"init():Source URL not specified");      
  59.         }      
  60.     }      
  61.      
  62.     public void start() {      
  63.         if (url != null)      
  64.         {      
  65.             if (jasperPrint == null)      
  66.             {      
  67.                 try     
  68.                 {      
  69.                  System.out.println("进入start方法,即将下载pdf文件");  
  70.                     jasperPrint = (JasperPrint)JRLoader.loadObject(url);    
  71.                     System.out.println("进入start方法,下载pdf文件完毕");  
  72.                 }      
  73.                 catch (Exception e)      
  74.                 {      
  75.                     StringWriter swriter = new StringWriter();      
  76.                     PrintWriter pwriter = new PrintWriter(swriter);      
  77.                     e.printStackTrace(pwriter);      
  78.                     JOptionPane.showMessageDialog(this, swriter.toString());      
  79.                 }      
  80.             }      
  81.                   
  82.             if (jasperPrint != null)      
  83.             {                     
  84.                 final JasperPrint print = jasperPrint;      
  85.                       
  86.                 Thread thread = new Thread      
  87.                     (      
  88.                         new Runnable()      
  89.                         {      
  90.                             public void run()      
  91.                             {      
  92.                                 try       
  93.                                 {      
  94.                                  System.out.println("进入start方法,即将打印pdf文件");  
  95.                                     JasperPrintManager.printReport(print, true);      
  96.                                 }      
  97.                                 catch (Exception e)       
  98.                                 {      
  99.                                     StringWriter swriter = new StringWriter();      
  100.                                     PrintWriter pwriter = new PrintWriter(swriter);      
  101.                                     e.printStackTrace(pwriter);      
  102.                                     JOptionPane.showMessageDialog(null, swriter.toString());      
  103.                                 }      
  104.                             }      
  105.                         }      
  106.                     );      
  107.                       
  108.                 thread.start();      
  109.             }      
  110.             else     
  111.             {      
  112.                 JOptionPane.showMessageDialog(this"Empty report.");      
  113.             }      
  114.         }      
  115.         else     
  116.         {      
  117.             JOptionPane.showMessageDialog(this"start():Source URL not specified");      
  118.         }      
  119.      
  120.     }      
  121.           
  122. }  

 

右键单击 JRPrinterApplet.java,选择 “Run as Java Applet”,弹出打印对话框,确认后打印机正常打印,证明 applet 已经编写成功。
8、jsp 页面嵌入 applet源码:

 

view plain print ?
  1. <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. >  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'index.jsp' starting pagetitle>  
  13.  <meta http-equiv="pragma" content="no-cache">  
  14.  <meta http-equiv="cache-control" content="no-cache">  
  15.  <meta http-equiv="expires" content="0">      
  16.  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  17.  <meta http-equiv="description" content="This is my page">  
  18.    
  19. head>   
  20. <mce:script language="javascript">

你可能感兴趣的:(JasperReports报表)