Maven + Struts2 + JasperReport + MSSQLServer2008 报表实现

我使用的是SpringSource ToolSuite开发工具(内核还是Eclipse)。

1.首先使用iReport工具自己做一个.jrxml结尾的报表文件。

2.配置好struts2的开发环境。

直接粘贴代码吧:

下面是Maven工程的路径

 

pom.xml(自动加载jar包的文件):

<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>com.banclogix.jasper</groupId>
  <artifactId>jasper</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>jasper Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <repositories>
        <repository>
            <id>jasperreports</id>
            <url>http://jasperreports.sourceforge.net/maven2</url>
        </repository>
    </repositories>
   
      <dependencies>
        <!-- <dependency>
            <groupId>ar.com.fdvs</groupId>
            <artifactId>DynamicJasper</artifactId>
            <version>3.0.13</version>
        </dependency>
         -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.2.1.1</version>
        </dependency>
       
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.1-alpha-1</version>
        </dependency>
       
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.10.0.GA</version>
            <scope>runtime</scope>
        </dependency>
       
        <dependency>
            <groupId>net.sourceforge.jtds</groupId>
            <artifactId>jtds</artifactId>
            <version>1.2.4</version>
        </dependency>
        <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.16</version>
          <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.0.2</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.8.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>2.1</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>commons-digester</groupId>
            <artifactId>commons-digester</artifactId>
            <version>1.7</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>1.7.5</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.6</version>
            <scope>compile</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>jfree</groupId>
            <artifactId>jcommon</artifactId>
            <version>1.0.15</version>
            <scope>compile</scope>
            <exclusions>
                <exclusion>
                    <groupId>gnujaxp</groupId>
                    <artifactId>gnujaxp</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>jfree</groupId>
            <artifactId>jfreechart</artifactId>
            <version>1.0.12</version>
            <scope>compile</scope>
            <exclusions>
                <exclusion>
                    <groupId>gnujaxp</groupId>
                    <artifactId>gnujaxp</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
  <build>
    <finalName>jasper</finalName>
  </build>
</project>

 

其他的Jar包:

 

 

struts.xml文件内容:

<?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>
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
    <constant name="struts.action.extension" value="action"/>

    <include file="example.xml"/>

    <!-- <package name="default" namespace="/" extends="struts-default">
        <default-action-ref name="index" />
        <action name="index">
            <result type="redirectAction">
                <param name="actionName">HelloWorldAction</param>
                <param name="namespace">/example</param>
            </result>
        </action>
    </package> -->

    <!-- Add packages here -->

</struts>

-------------------------------------------------------------------

example.xml文件内容:

<?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>
    <package name="export" namespace="/export" extends="struts-default">
        <action name="export_*" class="com.dmf.action.ExampleAction" method="{1}">
            <result name="export_html">/export/export_html.jsp?currency=${currency}</result>
            <!-- ../reports/image?image=px -->
            <!-- ../reports/px -->
            <result name="image"></result>
        </action>

        <!-- <action name="Login_*" method="{1}" class="example.Login">
            <result name="input">/example/Login.jsp</result>
            <result type="redirectAction">Menu</result>
        </action>

        <action name="*" class="example.ExampleSupport">
            <result>/example/{1}.jsp</result>
        </action> -->

        <!-- Add actions here -->
    </package>
   
    <package name="default"
        extends="struts-default,jasperreports-default">
        <action name="PDF" class="com.dmf.action.JasperAction">
            <result name="success" type="jasper">
                <param name="location">
                    /reports/compiled_KDF_Report07.jasper
                </param>
                <param name="dataSource">Quotes</param>
                <param name="format">PDF</param>
            </result>
        </action>
        <action name="HTML" class="com.dmf.action.JasperAction">
            <result name="success" type="jasper">
                <param name="location">
                    /reports/compiled_KDF_Report07.jasper
                </param>
                <param name="dataSource">Quotes</param>
                <param name="format">HTML</param>
            </result>
        </action>
        <action name="XML" class="com.dmf.action.JasperAction">
            <result name="success" type="jasper">
                <param name="location">
                    /reports/compiled_KDF_Report07.jasper
                </param>
                <param name="dataSource">Quotes</param>
                <param name="format">XML</param>
            </result>
        </action>
        <action name="CSV" class="com.dmf.action.JasperAction">
            <result name="success" type="jasper">
                <param name="location">
                    /reports/compiled_KDF_Report07.jasper
                </param>
                <param name="dataSource">Quotes</param>
                <param name="format">CSV</param>
            </result>
        </action>
        <action name="XLS" class="com.dmf.action.JasperAction">
            <result name="success" type="jasper">
                <param name="location">
                    /reports/compiled_KDF_Report07.jasper
                </param>
                <param name="dataSource">Quotes</param>
                <param name="format">XLS</param>
            </result>
        </action>
        <action name="RTF" class="com.dmf.action.JasperAction">
            <result name="success" type="jasper">
                <param name="location">
                    /reports/compiled_KDF_Report07.jasper
                </param>
                <param name="dataSource">Quotes</param>
                <param name="format">RTF</param>
            </result>
        </action>
    </package>
</struts>

------------------------------------------------------------------------

database.properties:

password=pass
url=jdbc/:jtds/:sqlserver/://yourIP:1433/databaseName
username=use
driver_name=net.sourceforge.jtds.jdbc.Driver
close_time=1200000

 

-------------------------------------------------------------------

JasperAction.java:

package com.dmf.action;

import java.io.File;
import java.util.List;

import net.sf.jasperreports.engine.JasperCompileManager;

import org.apache.struts2.ServletActionContext;

import com.dmf.db.DataBaseLayer;
import com.dmf.dto.Quote;
import com.opensymphony.xwork2.ActionSupport;

public class JasperAction extends ActionSupport {

    private static final long serialVersionUID = 1L;
//    private List<PeopleBean> myList;
    private List<Quote> quotes;
    private DataBaseLayer dataBaseLayer;

    public String execute() throws Exception {
        //From DB
        dataBaseLayer = DataBaseLayer.getInstance();
        quotes = dataBaseLayer.getQuotes();

        try {
            String reportSource = ServletActionContext.getServletContext()
                    .getRealPath("/reports/KDF_Report07.jrxml");
            File parent = new File(reportSource).getParentFile();
           
            JasperCompileManager.compileReportToFile(reportSource, new File(
                    parent, "compiled_KDF_Report07.jasper")
                    .getAbsolutePath());
           
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
        return SUCCESS;
    }

    public List getQuotes() {
        return quotes;
    }

}

 

---------------------------------------------------------------------

Constants.java:

public class Constants {
    public static final String DATABASEFILEPATH = "D://workspace//jasper//src//main//resources//database.properties";
}

 

---------------------------------------------------------------------------

ConfigReader.java:

package com.dmf.db;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;

/**read from file
 * @author limx */
public class ConfigReader {
    private static Logger logger = Logger.getLogger(ConfigReader.class);
    private static ConfigReader configReader;
    private Properties prop;
    private FileInputStream fis;
   
    public ConfigReader(){
       
    }
   
    /**
     * open properties file
     * @param fileName
     */
    public void init(String path){
        if(prop == null)
            prop = new Properties();
        try {
            fis = new FileInputStream(path);
            prop.load(fis);
        } catch (FileNotFoundException e) {
            logger.info("3 some error:"+e);
        }
        catch (IOException e) {
            logger.info("4 some error:"+e);
        }
    }
   
    /**Got a single class
     */
    public static synchronized ConfigReader getInstance(){
        if(configReader == null){
            configReader = new ConfigReader();
        }
        return configReader;
    }
   
    /**Got a item from config file
     */
    public String getConfigItem(String key,String defaultValue){
        return prop.getProperty(key, defaultValue);
    }

}

 

----------------------------------------------------------------------------------

ConnBean.java:

package com.dmf.db;

/**
 * @author limx
 */
public class ConnBean {
    private String driverName;
    private String url;
    private String username;
    private String password;
    public String getDriverName() {
        return driverName;
    }
    public void setDriverName(String driverName) {
        this.driverName = driverName;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
   
}

 

------------------------------------------------------------------

ConnectionPool.java

package com.dmf.db;

import java.sql.*;
import java.lang.reflect.*;
import java.util.*;
import java.io.*;

import org.apache.log4j.Logger;

import com.dmf.common.Constants;

@SuppressWarnings("unchecked")
/**@author limx
 * */
public class ConnectionPool {
    private static Logger logger = Logger.getLogger(ConnectionPool.class);
    @SuppressWarnings("rawtypes")
    private static LinkedList m_notUsedConnection = new LinkedList();
    @SuppressWarnings("rawtypes")
    private static HashSet m_usedUsedConnection = new HashSet();
    private static String m_url = "";
    private static String m_user = "";
    private static String m_password = "";
    private static String m_driver_name = "";
    private static long close_time = 10000;
    static final boolean DEBUG = true;
    static private long m_lastClearClosedConnection = System.currentTimeMillis();
   
    static {
        initConnectionPool();
        initDriver();
    }

    private ConnectionPool() {
    }
   
    private static void initConnectionPool(){
        ConfigReader configReader = ConfigReader.getInstance();
        configReader.init(Constants.DATABASEFILEPATH);
        ConnectionPool.setClose_time(Long.parseLong(configReader.getConfigItem("close_time", "120000000")));
        ConnectionPool.setPassword(configReader.getConfigItem("password", "kdf"));
        ConnectionPool.setUrl(configReader.getConfigItem("url", "kdf"));
        ConnectionPool.setUser(configReader.getConfigItem("username", "kdf"));
        ConnectionPool.setM_driver_name(configReader.getConfigItem("driver_name", ""));
    }

    private static void initDriver() {
        Driver driver = null;
        // load driver
        try {
            driver = (Driver) Class.forName(ConnectionPool.getM_driver_name())
                    .newInstance();
            installDriver(driver);
        } catch (Exception e) {
        }
    }

    public static void installDriver(Driver driver) {
        try {
            DriverManager.registerDriver(driver);
        } catch (Exception e) {
            System.out.println("ConnetionPool:installDriver");
            e.printStackTrace();
        }
    }

    @SuppressWarnings("rawtypes")
    public static synchronized Connection getConnection() {
        clearClosedConnection();
        while (m_notUsedConnection.size() > 0) {
            try {
                ConnectionWrapper wrapper = (ConnectionWrapper) m_notUsedConnection
                        .removeFirst();
                if (wrapper.connection.isClosed()) {
                    continue;
                }
                m_usedUsedConnection.add(wrapper);
                if (DEBUG) {
                    wrapper.debugInfo = new Throwable(
                    "Connection initial statement");
                }
                return wrapper.connection;
            } catch (Exception e) {
            }
        }
        int newCount = getIncreasingConnectionCount();
        LinkedList list = new LinkedList();
        ConnectionWrapper wrapper = null;
        for (int i = 0; i < newCount; i++) {
            wrapper = getNewConnection();
            if (wrapper != null) {
                list.add(wrapper);
            }
        }
        if (list.size() == 0) {
            return null;
        }
        wrapper = (ConnectionWrapper) list.removeFirst();
        m_usedUsedConnection.add(wrapper);

        m_notUsedConnection.addAll(list);
        list.clear();

        return wrapper.connection;
    }

    private static ConnectionWrapper getNewConnection() {
        try {
            Connection con = DriverManager.getConnection(m_url, m_user,
                    m_password);
            ConnectionWrapper wrapper = new ConnectionWrapper(con);
            return wrapper;
        } catch (Exception e) {
            String message = "DataBaseLayer:->getNewConnection failed!";
            logger.error(message+" "+e.toString());
        }
        return null;
    }

    static synchronized void pushConnectionBackToPool(ConnectionWrapper con) {
        boolean exist = m_usedUsedConnection.remove(con);
        if (exist) {
            m_notUsedConnection.addLast(con);
        }
    }

    @SuppressWarnings("rawtypes")
    public static int close() {
        int count = 0;

        Iterator iterator = m_notUsedConnection.iterator();
        while (iterator.hasNext()) {
            try {
                ((ConnectionWrapper) iterator.next()).close();
                count++;
            } catch (Exception e) {
            }
        }
        m_notUsedConnection.clear();

        iterator = m_usedUsedConnection.iterator();
        while (iterator.hasNext()) {
            try {
                ConnectionWrapper wrapper = (ConnectionWrapper) iterator.next();
                wrapper.close();
                if (DEBUG) {
                    wrapper.debugInfo.printStackTrace();
                }
                count++;
            } catch (Exception e) {
            }
        }
        m_usedUsedConnection.clear();

        return count;
    }

    @SuppressWarnings("rawtypes")
    private static void clearClosedConnection() {
        long time = System.currentTimeMillis();
        // sometimes user change system time,just return
        if (time < m_lastClearClosedConnection) {
            time = m_lastClearClosedConnection;
            return;
        }
        // no need check very often
        if (time - m_lastClearClosedConnection < close_time) {
            return;
        }
        m_lastClearClosedConnection = time;

        // begin check
        Iterator iterator = m_notUsedConnection.iterator();
        while (iterator.hasNext()) {
            ConnectionWrapper wrapper = (ConnectionWrapper) iterator.next();
            try {
                if (wrapper.connection.isClosed()) {
                    iterator.remove();
                }
            } catch (Exception e) {
                iterator.remove();
                if (DEBUG) {
                    System.out
                            .println("connection is closed, this connection initial StackTrace");
                    wrapper.debugInfo.printStackTrace();
                }
            }
        }

        // make connection pool size smaller if too big
        int decrease = getDecreasingConnectionCount();
        if (m_notUsedConnection.size() < decrease) {
            return;
        }

        while (decrease-- > 0) {
            ConnectionWrapper wrapper = (ConnectionWrapper) m_notUsedConnection
                    .removeFirst();
            try {
                wrapper.connection.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * get increasing connection count, not just add 1 connection
     *
     * @return count
     */
    public static int getIncreasingConnectionCount() {
        int count = 1;
        int current = getConnectionCount();
        count = current / 4;
        if (count < 1) {
            count = 1;
        }
        return count;
    }

    /**
     * get decreasing connection count, not just remove 1 connection
     *
     * @return count
     */
    public static int getDecreasingConnectionCount() {
        int current = getConnectionCount();
        if (current < 10) {
            return 0;
        }
        return current / 3;
    }

    public synchronized static void printDebugMsg() {
        printDebugMsg(System.out);
    }

    @SuppressWarnings({ "unused", "rawtypes" })
    public synchronized static void printDebugMsg(PrintStream out) {
        if (DEBUG == false) {
            return;
        }
        StringBuilder msg = new StringBuilder();
        msg.append("debug message in " + ConnectionPool.class.getName());
        msg.append("/r/n");
        msg.append("total count is connection pool: " + getConnectionCount());
        msg.append("/r/n");
        msg.append("not used connection count: " + getNotUsedConnectionCount());
        msg.append("/r/n");
        msg.append("used connection, count: " + getUsedConnectionCount());
        out.println(msg);
        Iterator iterator = m_usedUsedConnection.iterator();
        while (iterator.hasNext()) {
            ConnectionWrapper wrapper = (ConnectionWrapper) iterator.next();
            wrapper.debugInfo.printStackTrace(out);
        }
        out.println();
    }

    public static synchronized int getNotUsedConnectionCount() {
        return m_notUsedConnection.size();
    }

    public static synchronized int getUsedConnectionCount() {
        return m_usedUsedConnection.size();
    }

    public static synchronized int getConnectionCount() {
        return m_notUsedConnection.size() + m_usedUsedConnection.size();
    }

    public static String getUrl() {
        return m_url;
    }

    public static void setUrl(String url) {
        if (url == null) {
            return;
        }
        m_url = url.trim();
    }

    public static String getUser() {
        return m_user;
    }

    public static void setUser(String user) {
        if (user == null) {
            return;
        }
        m_user = user.trim();
    }

    public static String getPassword() {
        return m_password;
    }

    public static void setPassword(String password) {
        if (password == null) {
            return;
        }
        m_password = password.trim();
    }
   
    public static long getClose_time() {
        return close_time;
    }

    public static void setClose_time(long close_time) {
        ConnectionPool.close_time = close_time;
    }
   
    public static String getM_driver_name() {
        return m_driver_name;
    }

    public static void setM_driver_name(String m_driver_name) {
        ConnectionPool.m_driver_name = m_driver_name;
    }

}

class ConnectionWrapper implements InvocationHandler {
    private final static String CLOSE_METHOD_NAME = "close";
    public Connection connection = null;
    private Connection m_originConnection = null;
    public long lastAccessTime = System.currentTimeMillis();
    Throwable debugInfo = new Throwable("Connection initial statement");

    ConnectionWrapper(Connection con) {
        this.connection = (Connection) Proxy.newProxyInstance(con.getClass()
                .getClassLoader(), new Class[]{Connection.class}, this);
                //.getClassLoader(), con.getClass().getInterfaces(), this);
        m_originConnection = con;
    }

    void close() throws SQLException {
        m_originConnection.close();
    }

    public Object invoke(Object proxy, Method m, Object[] args)
            throws Throwable {
        Object obj = null;
        if (CLOSE_METHOD_NAME.equals(m.getName())) {
            ConnectionPool.pushConnectionBackToPool(this);
        } else {
            obj = m.invoke(m_originConnection, args);
        }
        lastAccessTime = System.currentTimeMillis();
        return obj;
    }
}

---------------------------------------------------------------------------------

DatabaseLayer.java:

package com.dmf.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.dmf.dto.Quote;

/** database operation
 *  @author limx
 */
public class DataBaseLayer {
    private static Logger logger = Logger.getLogger(DataBaseLayer.class);
    private static DataBaseLayer db = null;
    private Connection conn = null;
   
    synchronized public static DataBaseLayer getInstance(){
        if (db == null)
            db = new DataBaseLayer();
        return db;
    }
   
    /** connection
     */
    private DataBaseLayer(){
        try{
            conn = ConnectionPool.getConnection();
        }catch(Exception e){
            logger.error("DataBaseLayer:->getConnection failed!");
        }
    }
   
//    private PreparedStatement prstForSaveQuote = null;
//    private PreparedStatement getPrstForSelectQuote() throws SQLException {
//       
//        if (prstForSaveQuote == null)
//            prstForSaveQuote = conn.prepareStatement(
//                "select top 10 symbol,bid,ask from quote");
//        return prstForSaveQuote;
//    }
   
    public List<Quote> getQuotes(){
        List<Quote> quotes = null;
        PreparedStatement prst = null;
        ResultSet rs;
        String sql = "select top 50 symbol,bid,ask,quotetime from quote";
        try {
            prst = conn.prepareStatement(sql);
            rs = prst.executeQuery();
            Quote quote = null;
            if(quotes == null)
                quotes = new ArrayList<Quote>();
            while(rs.next()){
                quote = new Quote();
                quote.setBid(rs.getBigDecimal("bid"));
                quote.setAsk(rs.getBigDecimal("ask"));
                quote.setSymbol(rs.getString("symbol"));
                quote.setQuote_time(rs.getTimestamp("quotetime"));
                quotes.add(quote);
                quote = null;
            }
        } catch (SQLException e) {
            return new ArrayList<Quote>();
        }
       
        return quotes;
    }
   
    public static void main(String[] args){
        DataBaseLayer db = DataBaseLayer.getInstance();
        System.out.println(db.getQuotes().size());
    }
   
}
--------------------------------------------------------------------------------------------

Quote.java:

package com.dmf.dto;

import java.math.BigDecimal;
import java.sql.Timestamp;

/**
 * @author limx
 */
public class Quote {
    private String symbol;
    private BigDecimal bid;
    private BigDecimal ask;
    //private String data_source;
    private Timestamp quote_time;
   
    public Quote(){
       
    }
   
    public Quote(String symbol, BigDecimal bid, BigDecimal ask, Timestamp quote_time){
        this.symbol = symbol;
        this.bid = bid;
        this.ask = ask;
        //this.data_source = data_source;
        this.quote_time = quote_time;
    }
   
    public String getSymbol() {
        return symbol;
    }
    public void setSymbol(String symbol) {
        this.symbol = symbol;
    }
    public BigDecimal getBid() {
        return bid;
    }
    public void setBid(BigDecimal bid) {
        this.bid = bid;
    }
    public BigDecimal getAsk() {
        return ask;
    }
    public void setAsk(BigDecimal ask) {
        this.ask = ask;
    }
//    public String getData_source() {
//        return data_source;
//    }
//    public void setData_source(String data_source) {
//        this.data_source = data_source;
//    }
    public Timestamp getQuote_time() {
        return quote_time;
    }
    public void setQuote_time(Timestamp quote_time) {
        this.quote_time = quote_time;
    }
   
}
-------------------------------------------------------------------------------

index.jsp:

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Welcome</title>
</head>

<body style="text-align:center;">

<br/>
<font size="6" color="blue" style="font-weight:bloder;">Export Different Format File By *.jrxml File.</font>
<hr/>
<a href="HTML.action" target="_blank">From iReport.jrxml export [HTML]</a>
<br>
<a href="PDF.action" target="_blank">From iReport.jrxml export [PDF]</a>
<br>
<a href="XML.action" target="_blank">From iReport.jrxml export [XML]</a>
<br>
<a href="CSV.action" target="_blank">From iReport.jrxml export [CSV]</a>
<br>
<a href="XLS.action" target="_blank">From iReport.jrxml export [XLS]</a>
<br>
<a href="RTF.action" target="_blank">From iReport.jrxml export [RTF]</a>
<hr/>
</body>
</html>

-----------------------------------------------------------------------------------

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>Struts2 Jasper Demo</display-name>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>
-------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------------

KDF_Report07.jrxml:

<?xml version="1.0" encoding="UTF-8"?>
<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="KDF_Report07" language="groovy" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="30" rightMargin="30" topMargin="20" bottomMargin="20">
    <property name="ireport.scriptlethandling" value="0"/>
    <property name="ireport.encoding" value="UTF-8"/>
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <import value="net.sf.jasperreports.engine.*"/>
    <import value="java.util.*"/>
    <import value="net.sf.jasperreports.engine.data.*"/>
    <parameter name="rptMan" class="java.lang.String" isForPrompting="false">
        <defaultValueExpression><![CDATA["sterning"]]></defaultValueExpression>
    </parameter>
    <parameter name="rptDate" class="java.lang.String" isForPrompting="false">
        <defaultValueExpression><![CDATA["2008-01-12"]]></defaultValueExpression>
    </parameter>
    <field name="symbol" class="java.lang.String">
        <fieldDescription><![CDATA[symbol]]></fieldDescription>
    </field>
    <field name="bid" class="java.math.BigDecimal">
        <fieldDescription><![CDATA[bid]]></fieldDescription>
    </field>
    <field name="ask" class="java.math.BigDecimal">
        <fieldDescription><![CDATA[ask]]></fieldDescription>
    </field>
    <field name="quote_time" class="java.sql.Timestamp">
        <fieldDescription><![CDATA[quote_time]]></fieldDescription>
    </field>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="62" splitType="Stretch">
            <staticText>
                <reportElement key="staticText-1" x="7" y="0" width="517" height="57" forecolor="#FF0033"/>
                <box>
                    <topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                </box>
                <textElement textAlignment="Center">
                    <font size="36" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
                </textElement>
                <text><![CDATA[Struts2+JasperReports+MSSQL]]></text>
            </staticText>
            <line>
                <reportElement key="line-4" x="-30" y="61" width="594" height="1"/>
            </line>
        </band>
    </title>
    <pageHeader>
        <band height="13" splitType="Stretch">
            <line>
                <reportElement key="line-3" x="-29" y="12" width="592" height="1"/>
            </line>
        </band>
    </pageHeader>
    <columnHeader>
        <band height="45" splitType="Stretch">
            <staticText>
                <reportElement key="staticText-2" x="13" y="5" width="95" height="33"/>
                <box>
                    <topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                </box>
                <textElement>
                    <font size="24" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
                </textElement>
                <text><![CDATA[Symbol]]></text>
            </staticText>
            <staticText>
                <reportElement key="staticText-3" x="140" y="5" width="105" height="33"/>
                <box>
                    <topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                </box>
                <textElement>
                    <font size="24" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
                </textElement>
                <text><![CDATA[Bid]]></text>
            </staticText>
            <staticText>
                <reportElement key="staticText-4" x="266" y="5" width="100" height="33"/>
                <box>
                    <topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                </box>
                <textElement>
                    <font size="24" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
                </textElement>
                <text><![CDATA[Ask]]></text>
            </staticText>
            <staticText>
                <reportElement key="staticText-5" x="393" y="10" width="124" height="33"/>
                <box>
                    <topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                </box>
                <textElement>
                    <font size="24" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
                </textElement>
                <text><![CDATA[QuoteTime]]></text>
            </staticText>
            <line>
                <reportElement key="line-2" x="-30" y="43" width="596" height="1"/>
            </line>
        </band>
    </columnHeader>
    <detail>
        <band height="39" splitType="Stretch">
            <textField isBlankWhenNull="false">
                <reportElement key="textField-1" x="13" y="7" width="95" height="30"/>
                <box>
                    <topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                </box>
                <textElement>
                    <font size="14" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
                </textElement>
                <textFieldExpression class="java.lang.String"><![CDATA[$F{symbol}]]></textFieldExpression>
            </textField>
            <textField isBlankWhenNull="false">
                <reportElement key="textField-2" x="140" y="5" width="105" height="29"/>
                <box>
                    <topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                </box>
                <textElement>
                    <font size="14" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
                </textElement>
                <textFieldExpression class="java.math.BigDecimal"><![CDATA[$F{bid}]]></textFieldExpression>
            </textField>
            <textField isBlankWhenNull="false">
                <reportElement key="textField-3" x="266" y="5" width="100" height="28"/>
                <box>
                    <topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                </box>
                <textElement>
                    <font size="14" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
                </textElement>
                <textFieldExpression class="java.math.BigDecimal"><![CDATA[$F{ask}]]></textFieldExpression>
            </textField>
            <textField isBlankWhenNull="false">
                <reportElement key="textField-4" x="393" y="5" width="124" height="30"/>
                <box>
                    <topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                </box>
                <textElement>
                    <font size="14" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
                </textElement>
                <textFieldExpression class="java.sql.Timestamp"><![CDATA[$F{quote_time}]]></textFieldExpression>
            </textField>
            <line>
                <reportElement key="line-1" x="-30" y="37" width="593" height="1"/>
            </line>
        </band>
    </detail>
    <columnFooter>
        <band splitType="Stretch"/>
    </columnFooter>
    <pageFooter>
        <band height="50" splitType="Stretch">
            <textField isBlankWhenNull="false">
                <reportElement key="textField-8" x="98" y="18" width="138" height="23"/>
                <box>
                    <topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                </box>
                <textElement textAlignment="Right">
                    <font size="12" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
                </textElement>
                <textFieldExpression class="java.lang.String"><![CDATA["page " + String.valueOf($V{PAGE_NUMBER}) + " of"]]></textFieldExpression>
            </textField>
            <textField evaluationTime="Report" isBlankWhenNull="false">
                <reportElement key="textField-9" x="239" y="18" width="83" height="23"/>
                <box>
                    <topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                    <rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                </box>
                <textElement>
                    <font size="12" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
                </textElement>
                <textFieldExpression class="java.lang.String"><![CDATA[" " + String.valueOf($V{PAGE_NUMBER})]]></textFieldExpression>
            </textField>
        </band>
    </pageFooter>
    <lastPageFooter>
        <band height="50" splitType="Stretch"/>
    </lastPageFooter>
    <summary>
        <band splitType="Stretch"/>
    </summary>
</jasperReport>
----------------------------------------------------------------------------------------

参考网址:

http://www.blogjava.net/sterning/archive/2008/01/02/172317.html

 

OK 就是这些东西了,你只要按照这个区部署就可以了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值