struts.xml配置: java
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!--
(1)extends 加入 jasperreports-default
(2)result 加入 type="jasper"
(3)參數使用說明
location 指經過Ireport生成.jasper文件的路徑
datasource 若是是javabean source,使用此參數做爲數據源。
connection 若是是jdbc source,則使用此參數做爲數據源。
format 生成格式,XLS,HTML.CSV,默認爲PDF
-->
<package name="default" namespace="/"
extends="struts-default,jasperreports-default">
<action name="GeneratePDF" class="com.test.TestAction">
<result name="success" type="jasper">
<param name="location">/jasper/report1.jasper</param>
<param name="connection">conn</param>
<!-- <param name="dataSource">your javabean datasource</param> -->
<param name="format">PDF</param>
</result>
</action>
</package>
</struts>
sql
package com.test;
import java.sql.Connection;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport
{
private static final long serialVersionUID = 8006993549943492955L;
private Connection conn;
@Override
public String execute()
throws Exception
{
/*
* 在頁面跳轉以前將Connection賦值
*/
setConn(DBConnection.getInstance());
return SUCCESS;
}
public Connection getConn()
{
return conn;
}
public void setConn(Connection conn)
{
this.conn = conn;
}
}
數據庫
package com.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 用JDBC簡單獲取一個Connection鏈接提供給JasperReport使用
* @author Klaus_pi
*/
public class DBConnection
{
private static Connection instance = null;
private DBConnection()
{
}
public static Connection getInstance()
throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException
{
if (instance == null)
{
instance = getConn();
}
return instance;
}
public static Connection getConn()
throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException
{
String driver = "com.ibm.db2.jcc.DB2Driver";
String url = "jdbc:db2://192.168.1.66:50000/SAMPLE";
String userName = "db2admin";
String passWord = "db2admin";
Connection conn = null;
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url, userName, passWord);
return conn;
}
} apache