Jasperreports+jaspersoft studio學習教程(四)- JDBC嚮導作爲數據源填充數據

原文鏈接:https://blog.csdn.net/shiyun123zw/article/details/79166889

4.1 在studio工具中可以直接連接數據庫,利用sql語句檢索。創建數據庫,並建表

 

本教程使用mysql5.5+SQLyog工具,若沒有安裝,請百度自行安裝,創建DemoReport數據庫,並將user_tab表,注入數據如下:



 

4.2 在studio工具中新建JDBC數據源




然後Next ,選擇 Database JDBC Connection.





點擊Test 顯示 Successful! ,然後Finish!

 

4.3 新建報表模板

4.3.1 新建報表模板DemoReport3.jrxml,只保留Title Band 和 Detail Band.




4.3.2 模板右鍵 -> Dataset and QueryDialog



點擊OK 後,在outline中生成Field.




4.3.3 將id,user_name等拖入到 Detail 1 Band中設計模板如下:




點擊preview ,顯示如下:





4.4 在java程序中是用JDBC數據源

4.4.1 在JasperWeb項目中新建一個sevlet,加入mysql-connector-java-5.1.40-bin.jar依賴,並且將jrxml模板文件編譯爲jasper文件放入項目中。




4.4.2 JasperServlet2 的doGet內容:

  1. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  2. Map<String,Object> parameters = new HashMap<String,Object>(16);
  3. String jasperPath = request.getServletContext().getRealPath("/")+"/jasper/DemoReport3.jasper";
  4. PrintWriter out = null;
  5. try {
  6. String url = "jdbc:mysql://localhost/demoreport";
  7. Class.forName("com.mysql.jdbc.Driver");
  8. Connection conn = DriverManager.getConnection(url, "root", "123456");
  9. //通過JasperFillManager工具進行填充報表,生成JasperPring文件
  10. JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, parameters, conn);
  11. //將html輸出到瀏覽器上
  12. JRHtmlExporter exporter = new JRHtmlExporter();
  13. response.setCharacterEncoding("UTF-8");
  14. out = response.getWriter();
  15. exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
  16. exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out);
  17. exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
  18. exporter.exportReport();
  19. } catch (Exception e) {
  20. e.printStackTrace();
  21. }finally {
  22. out.flush();
  23. out.close();
  24. }
  25. }


4.4.3 啓動tomcat,並訪問:






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章