欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Jasperreports+jaspersoft studio学习教程(三)- JDBC向导作为数据源填充数据

程序员文章站 2022-05-18 17:08:47
...

转载:https://blog.csdn.net/shiyun123zw/article/details/79166889

4.1 在studio工具中可以直接连接数据库,利用sql语句检索。创建数据库,并建表

 

本教程使用mysql5.5+SQLyog工具,若没有安装,请百度自行安装,创建DemoReport数据库,并将user_tab表,注入数据如下:

 

Jasperreports+jaspersoft studio学习教程(三)- JDBC向导作为数据源填充数据

 

4.2 在studio工具中新建JDBC数据源

 

Jasperreports+jaspersoft studio学习教程(三)- JDBC向导作为数据源填充数据

然后Next ,选择 Database JDBC Connection.

Jasperreports+jaspersoft studio学习教程(三)- JDBC向导作为数据源填充数据

Jasperreports+jaspersoft studio学习教程(三)- JDBC向导作为数据源填充数据

Jasperreports+jaspersoft studio学习教程(三)- JDBC向导作为数据源填充数据

 

点击Test 显示 Successful! ,然后Finish!

4.3 新建报表模板

4.3.1 新建报表模板DemoReport3.jrxml,只保留Title Band 和 Detail Band.

Jasperreports+jaspersoft studio学习教程(三)- JDBC向导作为数据源填充数据

4.3.2 模板右键 -> Dataset and QueryDialog

Jasperreports+jaspersoft studio学习教程(三)- JDBC向导作为数据源填充数据

点击OK 后,在outline中生成Field.

Jasperreports+jaspersoft studio学习教程(三)- JDBC向导作为数据源填充数据

4.3.3 将id,user_name等拖入到 Detail 1 Band中设计模板如下:

Jasperreports+jaspersoft studio学习教程(三)- JDBC向导作为数据源填充数据

点击preview ,显示如下:

Jasperreports+jaspersoft studio学习教程(三)- JDBC向导作为数据源填充数据

4.4 在java程序中是用JDBC数据源

4.4.1 在JasperWeb项目中新建一个sevlet,加入mysql-connector-java-5.1.40-bin.jar依赖,并且将jrxml模板文件编译为jasper文件放入项目中。

 

Jasperreports+jaspersoft studio学习教程(三)- JDBC向导作为数据源填充数据

4.4.2 JasperServlet2 的doGet内容:
此地省略,往下看;

4.4.3 启动tomcat,并访问:

Jasperreports+jaspersoft studio学习教程(三)- JDBC向导作为数据源填充数据

我用的项目是Maven项目:

代码详情如下:

pom.xml 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>JasperReports</groupId>
  <artifactId>JasperReports02</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>JasperReports02 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <dependency>  
	    <groupId>net.sf.jasperreports</groupId>  
	    <artifactId>jasperreports</artifactId>  
	    <version>5.6.0</version>  
	</dependency> 
	
	
	<dependency>
	    <groupId>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>5.1.30</version>
	</dependency>
	
	<!-- 解决中文乱码 -->
	<dependency> 
	    <groupId>com.lowagie</groupId>
	    <artifactId>itextasian</artifactId>
	    <version>1.5.2</version>
	</dependency>
	
	<dependency>
	    <groupId>javax.servlet</groupId>
	    <artifactId>servlet-api</artifactId>
	    <version>2.5</version>
	</dependency>
    
  </dependencies>
  <build>
    <finalName>JasperReports02</finalName>
  </build>
</project>

JasperServletDb.java 

package com.accord.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;

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.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;

public class JasperServletDb extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public JasperServletDb() {
        super();
    }

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

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	ServletContext context = this.getServletConfig().getServletContext(); 	
		try {
			//JasperCompileManager.compileReportToFile("E:/report/DbReport.jrxml");
			JasperCompileManager.compileReportToFile(context.getRealPath("/jasper/DemoReport03.jrxml"));
		} catch (JRException e1) {
			e1.printStackTrace();
		}//编译jrxml文件,生成jasper文件

		File reportFile = new File(context.getRealPath("/jasper/DemoReport03.jasper"));
		if (!reportFile.exists())
			throw new JRRuntimeException("FileWebappReport.jasper "
					+ "not found. The report design must be compiledfirst.");
		String jasperPath = context.getRealPath("/jasper/DemoReport03.jasper");
		PrintWriter out = null;
		try {
			String url = "jdbc:mysql://localhost:3306/db_bank";
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection(url, "root", "123456");
            
            FileInputStream isRef = new FileInputStream(reportFile);
    		ServletOutputStream sosRef = response.getOutputStream();
    		try {
    			//JasperRunManager.runReportToPdfStream(isRef, sosRef, null,new JREmptyDataSource());
    			JasperRunManager.runReportToPdfStream(isRef, sosRef, null, conn);
    			response.setContentType("application/pdf");
    		} catch (Exception e) {
    		}finally{
    			sosRef.flush();
    			sosRef.close();
    		}
			/*//通过JasperFillManager工具进行填充报表,生成文件
            JasperPrint jasperPrint = JasperFillManager
            		.fillReport(jasperPath, null,conn);
          //将html输出到浏览器上
            JRHtmlExporter exporter = new JRHtmlExporter();
            response.setCharacterEncoding("UTF-8");
    		out = response.getWriter();
    		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
    		exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out);
    		exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
    		exporter.exportReport();*/
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			//out.flush();
			//out.close();
		}
		
		
    }

}

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
  	<servlet-name>JasperServlet</servlet-name>
  	<display-name>JasperServlet</display-name>
  	<description></description>
  	<servlet-class>com.accord.servlet.JasperServlet</servlet-class>
  </servlet>
  <servlet>
  	<servlet-name>JasperServletDb</servlet-name>
  	<display-name>JasperServletDb</display-name>
  	<description></description>
  	<servlet-class>com.accord.servlet.JasperServletDb</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>JasperServlet</servlet-name>
  	<url-pattern>/JasperServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
  	<servlet-name>JasperServletDb</servlet-name>
  	<url-pattern>/JasperServletDb</url-pattern>
  </servlet-mapping>
</web-app>

DemoReport03.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.6.0.final using JasperReports Library version 6.6.0  -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="DemoReport03" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="9070203f-ccf8-4d07-b92c-387acc1200a1">
	<property name="com.jaspersoft.studio.data.sql.tables" value=""/>
	<property name="com.jaspersoft.studio.data.defaultdataadapter" value="msql"/>
	<queryString language="SQL">
		<![CDATA[select * from company]]>
	</queryString>
	<field name="Id" class="java.lang.Integer">
		<property name="com.jaspersoft.studio.field.label" value="Id"/>
		<property name="com.jaspersoft.studio.field.tree.path" value="company"/>
	</field>
	<field name="name" class="java.lang.String">
		<property name="com.jaspersoft.studio.field.label" value="name"/>
		<property name="com.jaspersoft.studio.field.tree.path" value="company"/>
	</field>
	<background>
		<band splitType="Stretch"/>
	</background>
	<title>
		<band height="79" splitType="Stretch">
			<staticText>
				<reportElement x="230" y="24" width="100" height="30" uuid="33f7db34-0687-469c-b9fb-69023e73638d"/>
				<textElement>
				   <font fontName="宋体" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
				</textElement>
				<text><![CDATA[公司明细表]]></text>
			</staticText>
		</band>
	</title>
	<pageHeader>
		<band height="49" splitType="Stretch">
			<staticText>
				<reportElement x="208" y="10" width="139" height="30" uuid="746bdd39-9f31-4905-a700-91f57aea3cf7"/>
				<textElement>
				   <font fontName="宋体" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
				</textElement>
				<text><![CDATA[这是pdf的页眉]]></text>
			</staticText>
		</band>
	</pageHeader>
	<detail>
		<band height="125" splitType="Stretch">
			<textField>
				<reportElement x="130" y="23" width="116" height="20" uuid="f0c3ef36-e052-476f-853c-e94249dac976"/>
				<textElement>
				   <font fontName="宋体" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
				</textElement>
				<textFieldExpression><![CDATA[$F{Id}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="247" y="23" width="233" height="20" uuid="b80cb7b0-ce36-4957-934b-fe2a3f8d792b"/>
				<textElement>
				   <font fontName="宋体" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
				</textElement>
				<textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
			</textField>
		</band>
	</detail>
	<pageFooter>
		<band height="54" splitType="Stretch">
			<staticText>
				<reportElement x="213" y="18" width="134" height="30" uuid="b824b8c5-c31d-4d3e-9b4b-c07a26b11061"/>
				<textElement>
				   <font fontName="宋体" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
				</textElement>
				<text><![CDATA[这是pdf的页脚]]></text>
			</staticText>
		</band>
	</pageFooter>
</jasperReport>