DynamicReports:Java快速报表组件

澳门新葡亰3522平台游戏 1

本文由码农网 –
小峰原创,转载请看清文末的转载要求,欢迎参与我们的付费投稿计划!

 SingletonClient.getHttpClient().execute(post2,localContext);这里是采用httpclient组件提交http请求,需要导入相应的依赖

DynamicReports是一款相当敏捷的Java报表组件,并且是完全免费开源的。和之前介绍的JFreeChart不同,DynamicReports是报表和可视化图表相结合的,可以更加直观地展现和统计数据。DynamicReports是对JasperReports的扩展,完全可以不用专门的设计器来设计。

<!– httpclient –>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.2.1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpcore</artifactId>
      <version>4.2.1</version>
    </dependency>
    
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpmime</artifactId>
      <version>4.2.1</version>
    </dependency>
    
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient-cache</artifactId>
      <version>4.2.1</version>
    </dependency>
    
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>fluent-hc</artifactId>
      <version>4.2.1</version>
    </dependency>
    
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.6</version>
    </dependency>

澳门新葡亰3522平台游戏 1

    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.1.1</version>

DynamicReports的特点

  • 使用非常方便
  • 可继承的报表设计
  • 无需可视化设计工具
  • 可混合动态报表和静态报表

    </dependency> 

DynamicReports的使用方法

这里我们以MAVEN项目为例,你可以在项目中加入以下XML文件:

<dependency>
<groupId>net.sourceforge.dynamicreports</groupId>
<artifactId>dynamicreports-core</artifactId>
<version>3.0.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
</dependency>

Java代码如下:

public class SimpleReportDemo {

private static Connection getConn() throws ClassNotFoundException,
SQLException{
Class.forName(“com.mysql.jdbc.Driver”);
return(Connection)
DriverManager.getConnection(“jdbc:mysql://localhost/database”,
“username”, “password”);
}

public static void buildReport(Connection conn){
JasperReportBuilder report=DynamicReports.report();//创建空报表
//样式
StyleBuilder boldStl=DynamicReports.stl.style().bold();
StyleBuilder
boldCenteredStl=DynamicReports.stl.style(boldStl).setHorizontalAlignment(HorizontalAlignment.CENTER);
StyleBuilder
titleStl=DynamicReports.stl.style(boldCenteredStl).setFontSize(16);
StyleBuilder
columnTitleStl=DynamicReports.stl.style(boldCenteredStl).setBorder(DynamicReports.stl.pen1Point())
.setBackgroundColor(Color.LIGHT_GRAY);
report.columns(Columns.column(“ID”, “id”, DataTypes.integerType()).
setHorizontalAlignment(HorizontalAlignment.CENTER),//列
Columns.column(“手机号段”, “code”, DataTypes.stringType()),
Columns.column(“运营商”,”service”,DataTypes.stringType()),
Columns.column(“省份”,”province”,DataTypes.stringType()),
Columns.column(“城市”,”city”,DataTypes.stringType()),
Columns.column(“品牌”,”type”,DataTypes.stringType()))
.setColumnTitleStyle(columnTitleStl)
.setHighlightDetailEvenRows(true)
.title(Components.text(“手机号段”).setStyle(titleStl))//标题
.pageFooter(Components.pageXofY().setStyle(boldCenteredStl))//页角
.setDataSource(“select * from codesubinfo limit 20″, conn);//数据源
try {
//显示报表
report.show();
//生成PDF文件
//report.toPdf(new FileOutputStream(“D:/test.pdf”));
} catch (DRException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void main(String orgs[]){
try {
Connection conn=getConn();
buildReport(conn);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

DynamicReports作为一款Java报表和图表生成类库,其小巧和简单是一大亮点。

工具类SingletonClient.java

 public class SingletonClient {    

     
    private static final String CHARSET = “UTF-8”;  
    private static HttpClient singleHttpClient;  
  
    private SingletonClient() {  
    }  
  
    public static synchronized HttpClient getHttpClient() {  
        if (null == singleHttpClient) {  
            //exe = Executors.newFixedThreadPool(POOL_SIZE);
            
            HttpParams params = new BasicHttpParams();  
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
            HttpProtocolParams.setContentCharset(params, CHARSET);  
            HttpProtocolParams.setUseExpectContinue(params, true);  
            HttpProtocolParams  
                    .setUserAgent(  
                            params,  
                            “Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 GTB6 (.NET CLR 3.5.30729)”);           
            /* 连接超时 */  
            HttpConnectionParams.setConnectionTimeout(params, 5000);  
            /* 请求超时 */  
            HttpConnectionParams.setSoTimeout(params, 5000);  
  
            // 设置HttpClient支持的请求模式  
            SchemeRegistry schReg = new SchemeRegistry();  
            schReg.register(new Scheme(“http”, 80, PlainSocketFactory  
                    .getSocketFactory()));  
            schReg.register(new Scheme(“https”, 443, SSLSocketFactory  
                    .getSocketFactory()));  
            // 在最新版本的httpclient中ThreadSafeClientConnManager已被@Deprecated掉,这里使用PoolingClientConnectionManager。  
            //ClientConnectionManager conMgr = new PoolingClientConnectionManager(schReg);  
            PoolingClientConnectionManager conMgr = new PoolingClientConnectionManager(schReg);  
            conMgr.setMaxTotal(10);
            //HttpHost localhost = new HttpHost(“locahost”, 80);
            //conMgr.setMaxPerRoute(new HttpRoute(localhost), 50);
            
            singleHttpClient = new DefaultHttpClient(conMgr, params);
            
        }  
        return singleHttpClient;  
    }
}

UserContext .java

public class UserContext {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub        
        final HttpContext localContext=initContext();        
        try {
            Thread.sleep(1000);
澳门新葡亰3522平台游戏,        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

         List<BasicNameValuePair> list2= new ArrayList<BasicNameValuePair>();
            list2.add(new BasicNameValuePair(“__VIEWSTATE”,”/wEPDwUJNDYwODU2NjU1ZGQ=”));            
            list2.add(new BasicNameValuePair(“txbComment”,”我跟你拼了  哈哈”));
            list2.add(new BasicNameValuePair(“btnSubmint”,”提交评论”));
             final HttpPost post2=SingletonClient.getPost(“”, list2);
             
            Thread mythread=new Thread(new Runnable(){
             int minute=59;
             int second=16;
             int millisec=400;
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    SimpleDateFormat sdf2=new SimpleDateFormat(“yyyy年MM月dd日hh时mm分ss秒SSS毫秒”);
                    //int sec=0;
                    while(true)
                    {
                        
                        if(Calendar.getInstance().get(Calendar.MINUTE)==minute&&Calendar.getInstance().get(Calendar.SECOND)==second&&Calendar.getInstance().get(Calendar.MILLISECOND)>millisec)
                        {
                            try {
                                long start=System.currentTimeMillis();                                
                                HttpResponse httpResponse1 = SingletonClient.getHttpClient().execute(post2,localContext);
                                System.out.println(“响应代码1″+httpResponse1.getStatusLine().getStatusCode());
                                long end=System.currentTimeMillis();
                                System.out.println(“往返响应时间:”+(end-start));                                
                                break;
                                
                            } catch (ClientProtocolException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }                                
                            break;                            
                        }
                        System.out.println(sdf2.format(new Date()));
                        
                    }
                    
                }
                
            });            
            mythread.start();
    }
    public static HttpContext initContext()
    {
        List<BasicNameValuePair> list= new ArrayList<BasicNameValuePair>();    
        
        list.add(new BasicNameValuePair(“__EVENTTARGET”,””));
        list.add(new BasicNameValuePair(“__EVENTARGUMENT”,””));
        list.add(new BasicNameValuePair(“__VIEWSTATE”,”/wEPDwULLTE1MzYzODg2NzZkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBQtjaGtSZW1lbWJlcm1QYDyKKI9af4b67Mzq2xFaL9Bt”));
        list.add(new BasicNameValuePair(“__EVENTVALIDATION”,”/wEWBQLWwpqPDQLyj/OQAgK3jsrkBALR55GJDgKC3IeGDE1m7t2mGlasoP1Hd9hLaFoI2G05″));
        list.add(new BasicNameValuePair(“tbUserName”,”你的用户名”));
        list.add(new BasicNameValuePair(“tbPassword”,”你的密码”));
        list.add(new BasicNameValuePair(“btnLogin”,”登录”));
        
        HttpPost post=SingletonClient.getPost(“”, list);
        
        // 创建一个本地Cookie存储的实例  
        CookieStore cookieStore = new BasicCookieStore();  
        //创建一个本地上下文信息  
        HttpContext localContext = new BasicHttpContext();  
        //在本地上下问中绑定一个本地存储  
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);  
        
        try {
            
            HttpResponse httpResponse = SingletonClient.getHttpClient().execute(post,localContext);
            String status=”初始化失败”;    
            if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY )            {                
                status=”初始化成功”;                
            }
            // Do not feel like reading the response body
            // Call abort on the request object
            post.abort();
            System.out.println(status);
             
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return localContext;
        
    }