当前位置: 代码迷 >> ASP >> JasperReport+iReport+Applet+Servlet打造报表
  详细解决方案

JasperReport+iReport+Applet+Servlet打造报表

热度:1049   发布时间:2012-10-29 10:03:53.0
JasperReport+iReport+Applet+Servlet制作报表

项目是B/S的,标示层使用的是Openlaszlo,客户要求在打印的时候不需要选择打印的纸张类型,报表显示就直接打印,所以我在客户做了一个小应用程序。

需要的jar有:msbase.jar;mssqlserver.jar;msutil.jar;jasperreports-2.0.5-applet.jar;

jasperreports-1.3.3.jar;jasperreports-2.0.5-javaflow.jar

需要使用Ireport设计模板,放在reports目录下,载入*.jasper文件

<%@ page contentType="text/html;charset=UTF-8"%>
<%@page import="java.util.Enumeration"%>
<%@page import="java.net.URLDecoder"%>
<%
   String sql = request.getParameter("sql");
   sql="select * from authors";
   System.out.println("viewer.jsp  =========:"+sql);
  // System.out.println("viewer.jsp  =========:"+new String(condition.getBytes("ISO8859_1"),"UTF-8"));
%>
<html>
	<head>
	</head>
	<body>
		<!--"CONVERTED_APPLET"-->
		<!-- HTML CONVERTER -->
		<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
			codebase="http://java.sun.com/update/1.5.0/jinstall-1_5-windows-i586.cab#Version=5,0,0,5"
			WIDTH="100%" HEIGHT="100%">
			<PARAM NAME=CODE VALUE="ViewerApplet.class">
			<param name="scriptable" value="false">
			<PARAM NAME=CODEBASE VALUE="applet">
			<PARAM NAME=ARCHIVE
				VALUE="jasperreports-2.0.5-javaflow.jar,jasperreports-2.0.5-applet.jar,commons-collections-3.1.jar">
			<param name="type" value="application/x-java-applet;version=1.5">
			<PARAM NAME="sql" VALUE="<%=sql%>">
			<comment>
			<embed type="application/x-java-applet;version=1.5"
				\
            ARCHIVE="jasperreports-2.0.5-javaflow.jar,jasperreports-2.0.5-applet.jar,commons-collections-3.1.jar"
				\
            WIDTH="100%" 
            	\
            HEIGHT="100%"
				\
            CODE="ViewerApplet.class"
				\
            CODEBASE="applet"
				\
            ARCHIVE="jasperreports-2.0.5-javaflow.jar,jasperreports-2.0.5-applet.jar,commons-collections-3.1.jar"
				\
            scriptable="false"
				\
            sql="<%=sql%>"
				\
            scriptable=false
			pluginspage="http://java.sun.com/products/plugin/index.html#download">
				<noembed>
					</XMP>
				</noembed>
			</embed>
			</comment>
		</object>
	</body>
</html>

?做一个ViewerApplet的类,继承JApplet

import java.awt.BorderLayout;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLEncoder;

import javax.swing.JApplet;
import javax.swing.JOptionPane;

import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JRViewer;

public class ViewerApplet extends JApplet {

	public ViewerApplet() {
		initComponents();
	}

	private javax.swing.JPanel pnlMain;

	public void init() {

		try {
			//获取viewer.jsp的sql参数
			String sql = getParameter("sql");
			//使用URLEncoder对sql语句进行encode
			sql = URLEncoder.encode(sql, "UTF-8");
			//提交到servlet,使用servlet访问服务器端数据
			URL url = new URL(getCodeBase(), "../servlet/appletServlet?sql="
					+ sql);
			if (url != null) {
				//获取服务器的传递过来的JasperPrint对象
				JasperPrint jasperPrint = (JasperPrint) JRLoader
						.loadObject(url);
				//创建一个JRViewer
				 JRViewer viewer = new JRViewer(jasperPrint);
				 this.pnlMain.add(viewer, BorderLayout.CENTER);
			}
		} catch (Exception e) {
			StringWriter swriter = new StringWriter();
			PrintWriter pwriter = new PrintWriter(swriter);
			e.printStackTrace(pwriter);
			JOptionPane.showMessageDialog(this, swriter.toString());
		}
	}

	private void initComponents() {// GEN-BEGIN:initComponents
		pnlMain = new javax.swing.JPanel();
		pnlMain.setLayout(new java.awt.BorderLayout());
		getContentPane().add(pnlMain, java.awt.BorderLayout.CENTER);
	}

}

?创建一个AppletServlet类

package com.gddzmr.servlet;

import java.io.IOException;
import java.io.ObjectOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gddzmr.applet.ViewerService;

import net.sf.jasperreports.engine.JasperPrint;

public class AppletServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}
	 
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		try {
			//获取一个sql参数
			String sql = request.getParameter("sql");
			
			ViewerService service = new ViewerService();
			//获取JasperPrint对象
			JasperPrint jasperPrint = service.getJasper(request
					.getRealPath("/"), sql);
			//将JasperPrint转化为ObjectOutputStream数据流输出
			response.setContentType("application/octet-stream");
			ServletOutputStream out = response.getOutputStream();
			ObjectOutputStream os = new ObjectOutputStream(out);
			os.writeObject(jasperPrint);
			os.flush();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

创建;AppletService类,用于获取JasperPrint对象

package com.gddzmr.applet;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.gddzmr.db.DBManager;

import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRMapCollectionDataSource;

public class ViewerService {
	DBManager db = new DBManager();

	public JasperPrint getJasper(String realpath, String sql) throws Exception {
		db.openDB();
		//查询结果集
		ResultSet rs = db.executeQuery(sql);
		db.closeSTDB();
		//将ResultSet转化为一个List<HashMap>数组
		List list = db.getMapList(rs);
		Collection rows = list;
		//获取一个JasperPrint对象
		JasperPrint jasperPrint = setReportCollection(realpath
				+ "\\reports\\inboundReport.jasper", rows);
		return jasperPrint;
	}

	/**
	 * 获取JasperPrint对象
	 * 
	 * @param url
	 * @param list
	 * @return
	 * @throws Exception
	 */
	public JasperPrint setReportCollection(String url, Collection list)
			throws Exception {

		Map parameters = new HashMap();
		JRMapCollectionDataSource dataSource;
		//将list数据集转换为JRMapCollectionDataSource
		dataSource = new JRMapCollectionDataSource(list);
		//使用JasperFillManager填充JasperPrint对象
		JasperPrint jasperPrint = JasperFillManager.fillReport(url, parameters,
				dataSource);
		return jasperPrint;
	}
}

?最后创建一个DBManager获取数据

package com.gddzmr.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class DBManager {
	private String driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";

	private String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs";

	private String user = "sa";

	private String password = "";

	private Connection cnn;

	private Statement stat;

	private PreparedStatement ps;

	public DBManager() {
	}

	/**
	 * 新建一个数据库连接
	 * 
	 */
	public void openDB() {
		try {

			// 加载数据连接驱动
			Class.forName(driverName);
			// 获取数据库连接
			cnn = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Statement执行查询语句,返回查询的结果集
	 * 
	 * @param sql
	 * @return
	 */
	public ResultSet executeQuery(String sql) {
		try {
			stat = cnn.createStatement();
			return stat.executeQuery(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * Statement执行update,insert,delete语句,返回影响的行数
	 * 
	 * @param sql
	 * @return
	 */
	public int executeUpdate(String sql) {
		try {
			stat = cnn.createStatement();
			return stat.executeUpdate(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * Statement执行存储过程,返回ture/false
	 * 
	 * @param sql
	 * @return
	 */
	public boolean executeProcedural(String sql) {
		try {
			stat = cnn.createStatement();
			return stat.execute(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * prepareStatement执行查询语句,返回查询的结果集
	 * 
	 * @param sql
	 * @param list
	 * @return
	 */
	public ResultSet executeQuery(String sql, List list) {
		try {
			ps = cnn.prepareStatement(sql);
			if (list.size() != 0 && list != null) {
				for (int i = 0; i < list.size(); i++) {
					ps.setObject(i + 1, list.get(i));
				}
			}
			return ps.executeQuery(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * prepareStatement执行update,insert,delete语句,返回影响的行数
	 * 
	 * @param sql
	 * @param list
	 * @return
	 */
	public int executeUpdate(String sql, List list) {
		try {
			ps = cnn.prepareStatement(sql);
			if (list.size() != 0 && list != null) {
				for (int i = 0; i < list.size(); i++) {
					ps.setObject(i + 1, list.get(i));
				}
			}
			return ps.executeUpdate(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * prepareStatement执行存储过程,返回ture/false
	 * 
	 * @param sql
	 * @param list
	 * @return
	 */
	public boolean executeProcedural(String sql, List list) {
		try {
			ps = cnn.prepareStatement(sql);
			if (list.size() != 0 && list != null) {
				for (int i = 0; i < list.size(); i++) {
					ps.setObject(i + 1, list.get(i));
				}
			}
			return ps.execute(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 关闭数据库连接,释放statment
	 * 
	 */
	public void closeSTDB() {
		try {
			stat.close();
			cnn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 关闭数据库连接,释放PreparedStatement
	 * 
	 */
	public void closePSDB() {
		try {
			ps.close();
			cnn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 将ResultSet结果集,转换为List<HashMap>,为创建jasperPrint做准备
	 * @param rs
	 * @return
	 */
	public List getMapList(ResultSet rs) {
		ArrayList<HashMap> list = new ArrayList<HashMap>();
		ArrayList<String> nameList = new ArrayList<String>();
		try {
			// 获取字段名的数组
			ResultSetMetaData md = rs.getMetaData();
			for (int i = 1; i <= md.getColumnCount(); i++) {
				nameList.add(md.getColumnName(i));
			}
			// 根据字段名,获取rs中字段的值
			if (rs != null) {
				while (rs.next()) {
					HashMap map = new HashMap();
					for (int i = 0; i < nameList.size(); i++) {
						map.put(nameList.get(i), rs.getObject(nameList.get(i)));
					}
					list.add(map);
				}
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	public static void main(String[] args) {
		DBManager db = new DBManager();
		db.openDB();
		ResultSet rs = db.executeQuery("select * from authors");
		ArrayList<HashMap> list = new ArrayList<HashMap>();
		ArrayList<String> nameList = new ArrayList<String>();
		try {
			// 获取字段名数组
			ResultSetMetaData md = rs.getMetaData();
			for (int i = 1; i <= md.getColumnCount(); i++) {
				nameList.add(md.getColumnName(i));
			}

			if (rs != null) {
				while (rs.next()) {
					HashMap map = new HashMap();
					for (int i = 0; i < nameList.size(); i++) {
						System.out.println(nameList.get(i) + "===="
								+ rs.getObject(nameList.get(i)));
						map.put(nameList.get(i), rs.getObject(nameList.get(i)));
					}
					list.add(map);
				}
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		db.closeSTDB();

	}
}

?

1 楼 fengfan2008 2008-05-30  
很好, 楼主能不能发扬开源精神把源码贴出来啊!
2 楼 love1907 2008-10-02  
很好、。。。。。。。。。。
3 楼 lzmch 2008-10-02  
写这么多,你出的报表是什么样式?取数的逻辑是什么?先简单说说再写,别人也好看明白,你这样一上来就是代码,没什么实际意义。
4 楼 melody_5207 2008-10-27  
楼主~~可以告诉一下联系方式吗? 有问题请教
  我的QQ:414902377 MSN:jz_melody328@hotmail.com
   
5 楼 longlongriver 2008-10-27  
JasperReport3已经支持基于flash的报表展示了,可以更灵活的支持B/S下的报表展示了!
6 楼 melody_5207 2008-10-27  
longlongriver 写道
JasperReport3已经支持基于flash的报表展示了,可以更灵活的支持B/S下的报表展示了!

  有实例吗?
 
7 楼 longlongriver 2008-10-27  
melody_5207 写道
longlongriver 写道
JasperReport3已经支持基于flash的报表展示了,可以更灵活的支持B/S下的报表展示了!

  有实例吗?
 


下载的demo就带了一个web应用的样例,很详细!
8 楼 melody_5207 2008-11-04  
longlongriver 写道
melody_5207 写道
longlongriver 写道
JasperReport3已经支持基于flash的报表展示了,可以更灵活的支持B/S下的报表展示了!

  有实例吗?
 


下载的demo就带了一个web应用的样例,很详细!

谢谢~~请问demo什么地方可以下载?
9 楼 melody_5207 2008-11-04  
URL url = new URL(getCodeBase(), "../servlet/appletServlet?sql=" 

~~在web.xml里是怎么配置的??
  相关解决方案