`
hejianhuacn
  • 浏览: 70106 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

JasperReport 在Spring中的使用 问题

阅读更多
最近看了《JasperReports for Java Developers》,里面讲了怎么在Spring里使用JasperReport
照着里面的例子做了一下,例子是没有问题的,但是我把展现方式改为由JasperReportsHtmlView 展现就出问题了,所有的图片都出不来,是不是使用JasperReportsHtmlView还要配置其它的拦截器或是什么?我在Google里找了一通,也没能解决主要是E文不太好国外的论坛也找了,看得头大,所以把代码贴出来,那位用过的能指点一下,谢过了

web配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<display-name>ReportWebApp</display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>jasperSpring</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet 
        </servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>jasperSpring</servlet-name>
		<url-pattern>/jasperSpring/*</url-pattern>
	</servlet-mapping>
</web-app>


前台Jsp页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Generate Report</title>
	</head>
<body>
			Click on the button to generate the report.
<form name="reportForm" action="jasperSpring/report" method="get"><input
	type="submit" name="submitButton" value="Submit" /></form>
</body>
</html>


jasperSpring-servlet.xml的内容:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource" destroy-method="close">
		<property name="driverClassName">
			<value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value>
		</property>
		<property name="url">
			<value>jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=Northwind</value>
		</property>
		<property name="username">
			<value>sa</value>
		</property>
		<property name="password">
			<value>sa</value>
		</property>
	</bean>
	<bean id="publicUrlMapping"
		class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		<property name="mappings">
			<props>
				<prop key="report">jasperController</prop>
			</props>
		</property>
	</bean>
	<bean id="jasperController"
		class="net.aachina.jasperreport.JasperSpringController">
		<property name="dataSource">
			<ref local="dataSource" />
		</property>
	</bean>
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
		<property name="basename" value="views" />
	</bean>
	<bean id="ImageServlet" class="net.sf.jasperreports.j2ee.servlets.ImageServlet">
	</bean>
</beans>


引用
views.properties中的内容

report.class=org.springframework.web.servlet.view.jasperreports.JasperReportsPdfView
#report.class=org.springframework.web.servlet.view.jasperreports.JasperReportsHtmlView
#report.class=net.aachina.jasperreport.render.JasperReportsHtmlView
report.url=reports/ChartReportDemo.jasper


控制器JasperSpringController的源码:
package net.aachina.jasperreport;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import net.sf.jasperreports.engine.JRResultSetDataSource;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class JasperSpringController implements Controller {

	private DataSource dataSource;

	public ModelAndView handleRequest(HttpServletRequest request,	HttpServletResponse response) throws ServletException,	IOException, ClassNotFoundException, SQLException
	{
		
		return new ModelAndView("report", getModel());
	}

	@SuppressWarnings("unchecked")
	private Map getModel() throws ClassNotFoundException, SQLException
	{
		Connection connection;
		Statement statement;
		ResultSet resultSet;
		HashMap model = new HashMap();
		String query = "SELECT"+
			     " Employees.[LastName] AS Employees_LastName,"+
		              " Employees.[FirstName] AS Employees_FirstName,"+
		              " Employees.[EmployeeID] AS Employees_EmployeeID,"+
		              " Orders.[OrderID] AS Orders_OrderID,"+
		              " Orders.[OrderDate] AS Orders_OrderDate "+
		                "  FROM "+
" Employees INNER JOIN  Orders ON Employees.[EmployeeID] = Orders.[EmployeeID]";
		connection = dataSource.getConnection();
		statement = connection.createStatement();
		resultSet = statement.executeQuery(query);
		JRResultSetDataSource resultSetDataSource =new JRResultSetDataSource(resultSet);
		model.put("datasource", resultSetDataSource);
		return model;
		}
	
	public void setDataSource(DataSource dataSource) 
	{
		this.dataSource = dataSource;
	}
}


JasperReport页面在IReport中的效果:


页面输出PDF效果:


但把输出改为JasperReportsHtmlView页面上的所有图片都显示不出来,应该是还有什么属性值设置的不对,哪位知道的请指点一下,项目里面的Jar包太大了不然把整个项目都上传上来
  • 描述: PDF效果图
  • 大小: 42.5 KB
  • 大小: 35.5 KB
分享到:
评论
7 楼 アリス 2017-04-13  
楼主你这篇是我找到的最有水平的,能不能告诉我怎么把html报表和引用的图片打包成一个zip进行下载
6 楼 weiawe 2015-03-16  
5 楼 揣神再现 2008-08-05  
没有上传这个文件吗???ChartReportDemo.jasper
4 楼 htp2002 2007-12-12  
这样做,connection何时关闭?

以下做法供参考:将datasource(jdbc)作为一个value放入model,这样spring的jasper相关view就会取到这个datasource,进而获取connection,fillreport后由spring关闭connection。

请参考代码AbstractJasperReportsView.fillReport
		JRDataSource jrDataSource = getReportData(model);

		if (jrDataSource != null) {
			// Use the JasperReports JRDataSource.
			if (logger.isDebugEnabled()) {
				logger.debug("Filling report with JRDataSource [" + jrDataSource + "].");
			}
			return JasperFillManager.fillReport(this.report, model, jrDataSource);
		}

		else {
			if (this.jdbcDataSource == null) {
				this.jdbcDataSource = (DataSource) CollectionUtils.findValueOfType(model.values(), DataSource.class);
			}

			if (this.jdbcDataSource != null) {
				// Use the JDBC DataSource.
				if (logger.isDebugEnabled()) {
					logger.debug("Filling report with JDBC DataSource [" + this.jdbcDataSource + "].");
				}
				Connection con = this.jdbcDataSource.getConnection();
				try {
					return JasperFillManager.fillReport(this.report, model, con);
				}
				finally {
					try {
						con.close();
					}
					catch (SQLException ex) {
						logger.debug("Could not close JDBC Connection", ex);
					}
				}
			}

			else {
				// Assume that the model contains parameters that identify
				// the source for report data (e.g. Hibernate or JPA queries).
				return JasperFillManager.fillReport(this.report, model);
			}
		}
3 楼 hejianhuacn 2007-11-12  
在上面的Controller中传入的是JRResultSetDataSource 如何传入Connection?因为报表文件里已经存在SQL语句了,如何直接传入Connection呢?这样最少页面看上去要整齐一点
2 楼 hejianhuacn 2007-11-07  
终于解决了!
方法来源于:http://forum.springframework.org/showthread.php?t=25030 其实自己也应该想到的BS一下自己。为了不让后来人受累,我把代码再Copy过来使帖子完整^_^

package net.aachina.jasperreport.render;

import java.io.ByteArrayOutputStream;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.ui.jasperreports.JasperReportsUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsSingleFormatView;
import org.springframework.web.util.WebUtils;

import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.j2ee.servlets.ImageServlet;

public class JasperReportsHtmlViewExtend extends
		AbstractJasperReportsSingleFormatView {

	private static final int OUTPUT_BYTE_ARRAY_INITIAL_SIZE = 4096;

	public JasperReportsHtmlViewExtend() {
		setContentType("text/html; charset=UTF-8");
	}

	protected JRExporter createExporter() {
		JRHtmlExporter jrHtmlExporter = new JRHtmlExporter();
		jrHtmlExporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,
				"image?image=");
		return jrHtmlExporter;
	}

	protected boolean useWriter() {
		return true;
	}

	@Override
	protected void renderReport(JasperPrint populatedReport, Map model,
			HttpServletResponse response) throws Exception {
		// TODO 自动生成方法存根
		if (model.containsKey("requestObject")) {
			HttpServletRequest request = (HttpServletRequest) model
					.get("requestObject");
			request.getSession().setAttribute(
					ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
					populatedReport);

		}
		// Prepare report for rendering.
		JRExporter exporter = createExporter();

		// Set exporter parameters - overriding with values from the Model.
		Map mergedExporterParameters = mergeExporterParameters(model);
		if (!CollectionUtils.isEmpty(mergedExporterParameters)) {
			exporter.setParameters(mergedExporterParameters);
		}

		if (useWriter()) {
			// We need to write text to the response Writer.

			// Copy the encoding configured for the report into the response.
			String contentType = getContentType();
			String encoding = (String) exporter
					.getParameter(JRExporterParameter.CHARACTER_ENCODING);
			if (encoding != null) {
				// Only apply encoding if content type is specified but does not
				// contain charset clause already.
				if (contentType != null
						&& contentType.toLowerCase().indexOf(
								WebUtils.CONTENT_TYPE_CHARSET_PREFIX) == -1) {
					contentType = contentType
							+ WebUtils.CONTENT_TYPE_CHARSET_PREFIX + encoding;
				}
			}
			response.setContentType(contentType);

			// Render report into HttpServletResponse's Writer.
			JasperReportsUtils.render(exporter, populatedReport, response
					.getWriter());
		}

		else {
			// We need to write binary output to the response OutputStream.

			// Apply the content type as specified - we don't need an encoding
			// here.
			response.setContentType(getContentType());

			// Render report into local OutputStream.
			// IE workaround: write into byte array first.
			ByteArrayOutputStream baos = new ByteArrayOutputStream(
					OUTPUT_BYTE_ARRAY_INITIAL_SIZE);
			JasperReportsUtils.render(exporter, populatedReport, baos);

			// Write content length (determined via byte array).
			response.setContentLength(baos.size());

			// Flush byte array to servlet output stream.
			ServletOutputStream out = response.getOutputStream();
			baos.writeTo(out);
			out.flush();
		}
	}

}

看代码就应该能明白了,哎 为什么我就没想到这么写呢

对了控制器里面也要修改一下:
package net.aachina.jasperreport;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import net.sf.jasperreports.engine.JRResultSetDataSource;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class JasperSpringController implements Controller {

	private DataSource dataSource;

	public ModelAndView handleRequest(HttpServletRequest request,	HttpServletResponse response) throws ServletException,	IOException, ClassNotFoundException, SQLException
	{
		
		return new ModelAndView("report", getModel(request));
	}

	@SuppressWarnings("unchecked")
	private Map getModel(HttpServletRequest request) throws ClassNotFoundException, SQLException
	{
		Connection connection;
		Statement statement;
		ResultSet resultSet;
		HashMap model = new HashMap();
		String query = "SELECT"+
						    " Employees.[LastName] AS Employees_LastName,"+
						    " Employees.[FirstName] AS Employees_FirstName,"+
						    " Employees.[EmployeeID] AS Employees_EmployeeID,"+
						    " Orders.[OrderID] AS Orders_OrderID,"+
						    " Orders.[OrderDate] AS Orders_OrderDate "+
					   "  FROM "+
					     	" Employees INNER JOIN  Orders ON Employees.[EmployeeID] = Orders.[EmployeeID]";
		connection = dataSource.getConnection();
		statement = connection.createStatement();
		resultSet = statement.executeQuery(query);
		JRResultSetDataSource resultSetDataSource =new JRResultSetDataSource(resultSet);
		model.put("datasource", resultSetDataSource);
		model.put("requestObject",request);
		System.out.println("well done!");
		return model;
		}
	
	public void setDataSource(DataSource dataSource) 
	{
		this.dataSource = dataSource;
	}
}
1 楼 hejianhuacn 2007-11-07  
直接使用Servlet 可以正确的输出为HTML,代码为:
package net.aachina.jasperreport;

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

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

import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.j2ee.servlets.ImageServlet;

public class HtmlReportServlet extends HttpServlet {
	public static final String REPORT_DIRECTORY = "/reports";

	protected void doGet(HttpServletRequest request,
	HttpServletResponse response) throws ServletException, IOException {
		Connection connection;
		ServletContext context = this.getServletConfig().getServletContext();
		String reportName = "ChartReportDemo";
		PrintWriter printWriter = response.getWriter();
		InputStream reportStream = getServletConfig().getServletContext()
				.getResourceAsStream(
						"/" + REPORT_DIRECTORY + "/" + reportName + ".jasper");
		JasperPrint jasperPrint;
		try {
			Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
			connection = DriverManager
					.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=Northwind","sa","sa");
			
			
			jasperPrint = JasperFillManager.fillReport(reportStream,
					new HashMap(), connection);
			JRHtmlExporter htmlExporter = new JRHtmlExporter();
			response.setContentType("text/html");
			request.getSession().setAttribute(
					ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
					jasperPrint);
			
			htmlExporter.setParameter(JRExporterParameter.JASPER_PRINT,
					jasperPrint);
			htmlExporter.setParameter(JRExporterParameter.OUTPUT_WRITER,
					printWriter);
			htmlExporter.setParameter(JRHtmlExporterParameter.CHARACTER_ENCODING, "gb2312");
			htmlExporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,
					"image?image=");
			htmlExporter.exportReport();
			connection.close();
			System.out.println("done!");
		} catch (Throwable t) {
			// display stack trace in the browser
			t.printStackTrace(printWriter);
		}
	}
}



web.xml修改为:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<display-name>
	ReportWebApp</display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>jasperSpring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet>
		<servlet-name>ImageServlet</servlet-name>
		<servlet-class>net.sf.jasperreports.j2ee.servlets.ImageServlet</servlet-class>
	</servlet>
	<servlet>
		<servlet-name>HtmlReportServlet</servlet-name>
		<servlet-class>
			net.aachina.jasperreport.HtmlReportServlet
		</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>jasperSpring</servlet-name>
		<url-pattern>/jasperSpring/*</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>HtmlReportServlet</servlet-name>
		<url-pattern>/htmlReport</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>ImageServlet</servlet-name>
		<url-pattern>/image</url-pattern>
	</servlet-mapping>
</web-app>


index.jsp的form action修改为:htmlReport

输出效果:图片上传不知道怎么编辑^_^

相关推荐

    jasperReport +spring 的使用

    - 在Spring环境中配置jasperReport,主要是通过Spring的配置文件(例如applicationContext.xml)进行。 - 配置数据源、jasperReport相关的bean以及任何其他必要的配置信息。 #### 三、报表设计与数据填充 1. **...

    jasperreport6 导出pdf中文不显示问题解决方式

    jasperreport6版本以上已经对pdf font name、pdf encoding等配置弃用,而改为使用font配置字体,所以以前使用itext jar包的方式已经不能解决pdf中文不显示问题,那么修改fonts中的字体文件,可以一劳永逸解决该问题...

    springmvc集成jasperreport

    在Spring MVC框架中集成JasperReport,主要是为了利用JasperReport强大的报表生成能力,将数据库中的数据以美观、直观的方式展现出来。以下是对这个过程的详细步骤和知识点的阐述: 1. **配置Servlet映射**: 在`...

    springmvc+jasperreport解决了中文显示和国际化

    在Spring MVC中集成JasperReport,能够方便地在Web应用中展示复杂的数据报表,同时解决中文显示和国际化的问题,使得报表能够适应多语言环境。 在Spring MVC项目中集成JasperReport,首先需要在`pom.xml`文件中添加...

    JasperReport实例导入可用

    在这个实例中,我们将探讨如何导入并使用一个可用的 JasperReport 示例项目,以理解其工作原理和核心功能。 1. **JasperReport 概述** JasperReport 提供了丰富的模板设计功能,支持多种数据源,如 JDBC、CSV、XML...

    spring项目jasperReportDemo演示

    在Spring项目中使用JasperReport,首先需要在`pom.xml`中添加JasperReport及其相关依赖。这可能包括`jasperreports`、`jfreechart`、`poi`等,这些库支持报表的生成和样式处理。确保正确地配置Maven依赖后,就可以...

    springmvc 集成jasperReport.docx

    本文旨在详细介绍如何将Spring MVC框架与JasperReport报表工具进行有效集成的过程,并解决在此过程中可能遇到的问题。JasperReport是一款非常强大的报表生成工具,它支持多种数据源,如JDBC、XML等,并且可以输出PDF...

    JasperReport报表设计总结

    例如,在使用JDBC连接时,可以利用Spring框架的特性来管理数据库连接,简化代码的编写。 ##### 3. 报表预览与打印 JasperReport提供了丰富的API来实现报表的预览和打印功能。一旦报表设计完成并通过数据填充后,...

    Struts2与Jasperreport报表结合

    Struts2和JasperReport是两个在Java Web开发中广泛使用的框架。Struts2作为MVC(模型-视图-控制器)架构的一部分,主要用于处理HTTP请求并管理应用程序流程,而JasperReport则是一个强大的报告生成工具,能够创建...

    springmvc+jasperReport5.6.0

    3. 在服务层中使用JasperFillManager填充报表并转换为JasperPrint对象。 4. 在控制器中,使用` JasperExportManager`将JasperPrint对象导出为PDF或其它格式,然后通过`HttpServletResponse`的`setContentType`和`...

    jasperReport详细教程及例子

    - **表达式语言**: 使用JasperReport的内置脚本语言JRExpression,可以在报表中执行计算、条件判断等操作。 ### 2. JasperReport组件 - **字段(Fields)**: 报表数据的来源,对应数据源中的列。 - **文本框(Text...

    JasperReport浏览器输出PDF为空白页的解决方案

    标题中的“JasperReport浏览器输出PDF为空白页”通常意味着在使用JasperReport生成PDF报表时,浏览器未能正确显示内容。这可能是由多种原因引起的,包括但不限于以下几点: 1. **XML解析错误**:`test.jrxml`文件是...

    spring MVC Web应用中集成Jasper报表工具

    同时,为了在Web环境中使用,可能还需要配置Maven或Gradle的依赖,确保所有必要的JasperReports库都已引入。 总结来说,Spring MVC结合JasperReports可以实现高效的数据可视化,通过自定义数据源、报表渲染和...

    jasperreport 教程

    **JasperReport 深度解析教程** JasperReport 是一款强大的...总之,JasperReport 是一个功能强大且灵活的报表工具,通过本教程的学习,你将能够熟练掌握其设计、开发和使用技巧,从而在项目中生成专业级别的报表。

    springboot整合JasperReport实现报表功能

    SpringBoot是一款轻量级的Java应用框架,它简化了在Spring框架上构建应用程序的过程。而JasperReport是一款强大的开源报表工具,能够帮助开发者创建、设计和展示复杂的业务报告。将两者整合,可以让SpringBoot应用...

    springmvc框架整合jasperreport和ireport简单易用框架清晰maven

    springmvc框架整合jasperreport和ireport简单易用,框架清晰,maven仓库

    Jasperreport资料

    JasperReport是一款强大的开源报表工具,它允许开发者在Java应用程序中创建复杂的报表。作为一个基于纯Java的报表引擎,JasperReport能够处理多种数据源,包括数据库连接、XML文件、Java集合等,生成各种格式的报表...

    JasperReport+SSH

    - 在Spring中实现业务逻辑,可能涉及到与Hibernate的交互,如查询数据库,获取数据。 - Hibernate负责与数据库进行交互,执行SQL语句,返回结果集。 - 结果集被传递给JasperReport,生成报表,然后以所需的格式(如...

Global site tag (gtag.js) - Google Analytics