Java程序调用iReport(傻瓜式教程)

1、新建一个Web Project:iReportTest

Java程序调用iReport(傻瓜式教程)_第1张图片

2、拷贝iReport提供的jar包(根据所使用的iReport版本导入)以及数据库驱动jar到WEB-INF下的lib目录下

Java程序调用iReport(傻瓜式教程)_第2张图片

3、新建一个Servlet:IreportServlet(不过多叙述)

Java程序调用iReport(傻瓜式教程)_第3张图片


4、编写IreportServlet

package com.sunyanbo.web.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JasperRunManager;

@SuppressWarnings("serial")
public class IreportServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);

	}

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

		try {
			response.setContentType("text/html; charset=UTF-8");
			request.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			Connection conn = null;
			File iReportFile = new File(this.getServletConfig()
					.getServletContext().getRealPath("/iReport/sample.jasper"));//使用iReport生成的文件,在WebRoot目录下新建
                                         //iReport文件夹,并把sample.jasper拷贝到该目录下
			Class.forName("oracle.jdbc.driver.OracleDriver");
			Map params = new HashMap();
			params.put("QUERY_USER_SQL", "SELECT * FROM AQ_YHXXB T");//iReport中设置了一个名称为QUERY_USER_SQL的参数
			conn = DriverManager.getConnection(
					"jdbc:oracle:thin:@127.0.0.1:jydb26", "ptas",
					"ptas");
			JasperRunManager.runReportToHtmlFile(iReportFile.getPath(), params,
					conn);//自动生成一个html文件,与sample.jasper位于同一目录下
			response.sendRedirect("/iReportTest/iReport/sample.html");//这里的sample.html是自动生成的,与sample.jasper位于同一目录下
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
5、浏览器输入http://localhost:8080/iReportTest/servlet/IreportServlet

Java程序调用iReport(傻瓜式教程)_第4张图片

【附录】iReport中QUERY_USER_SQL参数的设置

Java程序调用iReport(傻瓜式教程)_第5张图片

你可能感兴趣的:(数据库与JDBC)