当前位置:  开发笔记 > 编程语言 > 正文

如何将mongodb的连接对象提供给JasperFillManager.fillReport() - Spring MongoDB Jasper Integration

如何解决《如何将mongodb的连接对象提供给JasperFillManager.fillReport()-SpringMongoDBJasperIntegration》经验,为你挑选了0个好方法。

我正在研究Spring MongoDB Jasper集成示例.我有Spring Mysql Jasper示例,它工作正常.我希望转换为mongodb的相同程序.

源代码:https://github.com/test512/spring-mvc-mongo-jasper.git

@Note:我关注了http://jasperreports.sourceforge.net/api/index.html,但我没有看到要下载的jar文件.它不存在于maven回购中?

LoadJasperReport.java

@Controller
public class LoadJasperReport {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoadJasperReport.class);

    @ModelAttribute("jasperRptFormats")
    public ArrayList getJasperRptFormats() {
        ArrayList jasperRptFormats = new ArrayList();
        jasperRptFormats.add("Html");
        jasperRptFormats.add("PDF");

        return jasperRptFormats;
    }

    @RequestMapping(value = "/loadJasper", method = RequestMethod.GET)
    public String loadSurveyPg(@ModelAttribute("jasperInputForm") JasperInputForm jasperInputForm, Model model) {
        model.addAttribute("JasperInputForm", jasperInputForm);
        return "loadJasper";
    }

    @RequestMapping(value = "/generateReport", method = RequestMethod.POST)
    public String generateReport(@Valid @ModelAttribute("jasperInputForm") JasperInputForm jasperInputForm,
            BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response)
            throws ParseException {
        LOGGER.debug("~~~ Generate Report ~~~");

        if (result.hasErrors()) {
            LOGGER.error("validation error occured in jasper input form");
            return "loadJasper";

        }

        String reportFileName = "JREmp1";

        Connection conn = null;
        try {
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                LOGGER.error("Please include Classpath Where your MySQL Driver is located");
                e.printStackTrace();
            }

            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
            if (conn != null)
                LOGGER.debug("Database Connected");
            else
                LOGGER.debug(" connection Failed ");

            String rptFormat = jasperInputForm.getRptFmt();
            String noy = jasperInputForm.getNoofYears();

            LOGGER.debug("rpt format " + rptFormat + ", no of years " + noy);

            HashMap hmParams = new HashMap();
            hmParams.put("noy", new Integer(noy));
            hmParams.put("Title", "Employees working more than " + noy + " Years");

            JasperReport jasperReport = getCompiledFile(reportFileName, request);

            if (rptFormat.equalsIgnoreCase("html")) {
                JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, hmParams, conn);
                // For HTML report
                generateReportHtml(jasperPrint, request, response);
            } else if (rptFormat.equalsIgnoreCase("pdf")) {
                // For PDF report
                generateReportPDF(response, hmParams, jasperReport, conn);
            }
        } catch (Exception sqlExp) {
            LOGGER.error("Exception::" + sqlExp.toString());
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException expSQL) {
                LOGGER.error("SQLExp::CLOSING::" + expSQL.toString());
            }
        }
        return null;
    }

    private JasperReport getCompiledFile(String fileName, HttpServletRequest request) throws JRException {
        LOGGER.debug("path " + request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));

        File reportFile = new File(
                request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));

        // If compiled file is not found, then compile XML template
        if (!reportFile.exists()) {
            JasperCompileManager.compileReportToFile(
                    request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jrxml"),
                    request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
        }

        JasperReport jasperReport = (JasperReport) JRLoader.loadObjectFromFile(reportFile.getPath());
        return jasperReport;
    }

    private void generateReportHtml(JasperPrint jasperPrint, HttpServletRequest req, HttpServletResponse resp)
            throws IOException, JRException {
        LOGGER.debug("~~~ Generate HTML Report ~~~");

        HtmlExporter exporter = new HtmlExporter();

        List jasperPrintList = new ArrayList();
        jasperPrintList.add(jasperPrint);

        exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
        exporter.setExporterOutput(new SimpleHtmlExporterOutput(resp.getWriter()));

        SimpleHtmlReportConfiguration configuration = new SimpleHtmlReportConfiguration();
        exporter.setConfiguration(configuration);
        exporter.exportReport();
    }

    private void generateReportPDF(HttpServletResponse resp, Map parameters, JasperReport jasperReport,
            Connection conn) throws JRException, NamingException, SQLException, IOException {
        LOGGER.debug("~~~ Generate PDF Report ~~~");

        byte[] bytes = null;
        bytes = JasperRunManager.runReportToPdf(jasperReport, parameters, conn);

        resp.reset();
        resp.resetBuffer();
        resp.setContentType("application/pdf");
        resp.setContentLength(bytes.length);
        ServletOutputStream ouputStream = resp.getOutputStream();
        ouputStream.write(bytes, 0, bytes.length);
        ouputStream.flush();
        ouputStream.close();
    }
}

这个程序我试图转换为MongoDB如下,但我不知道如何获得Connection对象?有没有办法从mongodb或任何其他方式获取连接对象为mongodb jasper编写代码?

现在我看到了问题:

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, hmParams, conn);

我改变了下面的代码,但它不起作用.请指导.

package net.javaonline.spring.jasper.controller;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.naming.NamingException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jaspersoft.mongodb.MongoDbDataSource;
import com.jaspersoft.mongodb.connection.MongoDbConnection;

import net.javaonline.spring.jasper.form.JasperInputForm;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.export.HtmlExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleHtmlExporterOutput;
import net.sf.jasperreports.export.SimpleHtmlReportConfiguration;

@Controller
public class LoadJasperReport {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoadJasperReport.class); 

    @ModelAttribute("jasperRptFormats")
    public ArrayList getJasperRptFormats(){
        ArrayList jasperRptFormats = new ArrayList();
        jasperRptFormats.add("Html");
        jasperRptFormats.add("PDF");

        return jasperRptFormats;
    }   


    @RequestMapping(value = "/loadJasper", method = RequestMethod.GET)
    public String loadSurveyPg(
            @ModelAttribute("jasperInputForm") JasperInputForm jasperInputForm,
            Model model) {
        model.addAttribute("JasperInputForm", jasperInputForm);
        return "loadJasper";
    }


    @RequestMapping(value = "/generateReport", method = RequestMethod.POST)
    public String generateReport(
            @Valid @ModelAttribute("jasperInputForm") JasperInputForm jasperInputForm,
            BindingResult result,Model model, 
            HttpServletRequest request, HttpServletResponse response) throws ParseException {
        LOGGER.debug("~~~ Generate Report ~~~");

        if (result.hasErrors()) {
            LOGGER.error("validation error occured in jasper input form");
            return "loadJasper";

        }

        String reportFileName = "JREmp1";
        MongoDbConnection conn = null;

        try {
            try {
                conn = new MongoDbConnection("mongodb://localhost:27017/mydb", null, null);
            } catch (JRException e) {
                System.out.println("JREException : "+e.getMessage());
            }

            Map parameters = new HashMap();
            parameters.put(MongoDbDataSource.QUERY_LANGUAGE, conn);

            String rptFormat = jasperInputForm.getRptFmt();
            String noy = jasperInputForm.getNoofYears();

            LOGGER.debug("rpt format " + rptFormat+", no of years " + noy);


            HashMap hmParams=new HashMap();
            hmParams.put("noy", new Integer(noy));
            hmParams.put("Title", "Employees working more than "+ noy + " Years");


            JasperReport jasperReport = getCompiledFile(reportFileName, request);

            if (rptFormat.equalsIgnoreCase("html") ) {
                JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, hmParams, conn);
                // For HTML report
                generateReportHtml(jasperPrint, request, response); 
            }
            else if(rptFormat.equalsIgnoreCase("pdf")){
                // For PDF report
                generateReportPDF(response, hmParams, jasperReport, conn); 
            }
        } catch (JRException | IOException | NamingException | SQLException e) {
            System.out.println(e.getMessage());
        } finally {
            if (conn != null) {
                conn.close();
                conn = null;
            }
        }
        return null;
    }

    private JasperReport getCompiledFile(String fileName, HttpServletRequest request) throws JRException {
        LOGGER.debug("path " + request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));

        File reportFile = new File( request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));

        // If compiled file is not found, then compile XML template
        if (!reportFile.exists()) {
            JasperCompileManager.compileReportToFile(request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jrxml"),request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
        }

        JasperReport jasperReport = (JasperReport) JRLoader.loadObjectFromFile(reportFile.getPath());
        return jasperReport;
    } 


    private void generateReportHtml( JasperPrint jasperPrint, HttpServletRequest req, HttpServletResponse resp) 
            throws IOException, JRException {
        LOGGER.debug("~~~ Generate HTML Report ~~~");

        HtmlExporter exporter=new HtmlExporter();

        List jasperPrintList = new ArrayList();
        jasperPrintList.add(jasperPrint);

        exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
        exporter.setExporterOutput( new SimpleHtmlExporterOutput(resp.getWriter()));

        SimpleHtmlReportConfiguration configuration =new SimpleHtmlReportConfiguration();
        exporter.setConfiguration(configuration);
        exporter.exportReport();
    }

    private void generateReportPDF (HttpServletResponse resp, Map parameters, 
            JasperReport jasperReport, Connection conn)throws JRException, NamingException, SQLException, IOException {
        LOGGER.debug("~~~ Generate PDF Report ~~~");

        byte[] bytes = null;
        bytes = JasperRunManager.runReportToPdf(jasperReport, parameters, conn);

        resp.reset();
        resp.resetBuffer();
        resp.setContentType("application/pdf");
        resp.setContentLength(bytes.length);
        ServletOutputStream ouputStream = resp.getOutputStream();
        ouputStream.write(bytes, 0, bytes.length);
        ouputStream.flush();
        ouputStream.close();
    } 
}

JREmp1.jrxml



    
    
    
    
        
    
    
    
    
    
    
        
    
    
        <band  splitType="Stretch">
            <staticText>
                <reportElement x="0" y="0"   uuid="52aef86d-1b56-49fa-bb20-e4b0ad93e554"/>
                <textElement textAlignment="Center">
                    <font size="15"/>
                </textElement>
                <text><![CDATA[OMS Order Report]]></text>
            </staticText>
        </band>
    
    
        
            
                
                
                
            
            
                
                
            
        
    
    
        
            
                
                
            
            
                
                
            
            
                
                
            
            
                
                
            
            
                
                
            
        
    
    
        
            
                
                
            
            
                
                
            
            
                
                
            
            
                
                
            
            
                
                
            
        
    
    
        
    
    
        
    
    
        
    

在此输入图像描述

推荐阅读
雯颜哥_135
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有