Maven + Struts2 + JasperReport + MSSQLServer2008 报表实现

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

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

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

直接粘贴代码吧:

下面是Maven工程的路径

 

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

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  4.0.0
  com.banclogix.jasper
  jasper
  war
  0.0.1-SNAPSHOT
  jasper Maven Webapp
  http://maven.apache.org
 
       
            jasperreports
            http://jasperreports.sourceforge.net/maven2
       

   

   
     
       
       
            junit
            junit
            3.8.1
            test
       


       
            javax.servlet
            servlet-api
            2.4
       

       
            javax.servlet.jsp
            jsp-api
            2.0
            provided
       


       
            org.apache.struts
            struts2-core
            2.2.1.1
       

       
       
            org.apache.maven.plugins
            maven-war-plugin
            2.1-alpha-1
       

       
       
            javassist
            javassist
            3.10.0.GA
            runtime
       

       
       
            net.sourceforge.jtds
            jtds
            1.2.4
       

       
          log4j
          log4j
          1.2.16
          compile
       

       
            commons-logging
            commons-logging
            1.0.2
            compile
       

       
            commons-beanutils
            commons-beanutils
            1.8.0
            compile
       

       
            commons-collections
            commons-collections
            2.1
            compile
       

       
            commons-digester
            commons-digester
            1.7
            compile
       

       
            org.codehaus.groovy
            groovy-all
            1.7.5
            compile
       

       
            org.apache.poi
            poi
            3.6
            compile
            true
       

       
            com.lowagie
            itext
            2.1.7
            compile
       

       
            jfree
            jcommon
            1.0.15
            compile
           
               
                    gnujaxp
                    gnujaxp
               

           

       

       
            jfree
            jfreechart
            1.0.12
            compile
           
               
                    gnujaxp
                    gnujaxp
               

           

       

   

 
    jasper
 

 

其他的Jar包:

 

 

struts.xml文件内容:


    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">


   
   
   

   

   

   

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

example.xml文件内容:


        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">


   
       
            /export/export_html.jsp?currency=${currency}
           
           
           
       


       

       
   

   
            extends="struts-default,jasperreports-default">
       
           
               
                    /reports/compiled_KDF_Report07.jasper
               
                Quotes
                PDF
           

       

       
           
               
                    /reports/compiled_KDF_Report07.jasper
               
                Quotes
                HTML
           

       

       
           
               
                    /reports/compiled_KDF_Report07.jasper
               
                Quotes
                XML
           

       

       
           
               
                    /reports/compiled_KDF_Report07.jasper
               
                Quotes
                CSV
           

       

       
           
               
                    /reports/compiled_KDF_Report07.jasper
               
                Quotes
                XLS
           

       

       
           
               
                    /reports/compiled_KDF_Report07.jasper
               
                Quotes
                RTF
           

       

   

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

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 myList;
    private List 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 getQuotes(){
        List 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();
            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();
        }
       
        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" %>


    Welcome






Export Different Format File By *.jrxml File.



From iReport.jrxml export [HTML]


From iReport.jrxml export [PDF]


From iReport.jrxml export [XML]


From iReport.jrxml export [CSV]


From iReport.jrxml export [XLS]


From iReport.jrxml export [RTF]



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

web.xml:

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


    Struts2 Jasper Demo
   
        struts2
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
   


   
        struts2
        /*
   


   
        index.html
   


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

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

KDF_Report07.jrxml:



   
   
   
   
   
   
   
   
   
       
   

   
       
   

   
       
   

   
       
   

   
       
   

   
       
   

   
       
   

    <br>         <band height="62" splitType="Stretch"><br>             <staticText><br>                 <reportElement key="staticText-1" x="7" y="0" width="517" height="57" forecolor="#FF0033"/><br>                 <box><br>                     <topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/><br>                     <leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/><br>                     <bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/><br>                     <rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/><br>                 </box><br>                 <textElement textAlignment="Center"><br>                     <font size="36" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/><br>                 </textElement><br>                 <text><![CDATA[Struts2+JasperReports+MSSQL]]></text><br>             </staticText><br>             <line><br>                 <reportElement key="line-4" x="-30" y="61" width="594" height="1"/><br>             </line><br>         </band><br>    
   
       
           
               
           

       

   

   
       
           
               
               
                   
                   
                   
                   
               

               
                   
               

               
           

           
               
               
                   
                   
                   
                   
               

               
                   
               

               
           

           
               
               
                   
                   
                   
                   
               

               
                   
               

               
           

           
               
               
                   
                   
                   
                   
               

               
                   
               

               
           

           
               
           

       

   

   
       
           
               
               
                   
                   
                   
                   
               

               
                   
               

               
           

           
               
               
                   
                   
                   
                   
               

               
                   
               

               
           

           
               
               
                   
                   
                   
                   
               

               
                   
               

               
           

           
               
               
                   
                   
                   
                   
               

               
                   
               

               
           

           
               
           

       

   

   
       
   

   
       
           
               
               
                   
                   
                   
                   
               

               
                   
               

               
           

           
               
               
                   
                   
                   
                   
               

               
                   
               

               
           

       

   

   
       
   

   


       
   


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

参考网址:

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

 

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

你可能感兴趣的:(Java,JasperReport)