JasperReports Servelet

I’m creating a report with JasperReports from JavaBeans, both excel and pdf. The files are being created in the disk. I want to call Jasper from a servlet so I can return the file (not filename, without writing it in the disk or if so, just temporarily).

This is my generateReport method (to the disk)

@ExtDirectMethod
public String generateReport(String[] headers, Object[] data,
        String language, String template, String title, String type)
        throws JRException, SQLException, IOException {

    HttpSession session = (HttpSession) RequestContextHolder
            .currentRequestAttributes().getSessionMutex();
    String path = session.getServletContext().getRealPath("/");

    final long startTime = System.nanoTime();

    System.out.println("Generating report...");
    JasperReport jasperReport = JasperCompileManager.compileReport(path
            + "Template/Instructions_with_CHGFOX_Template/teste.jrxml");

    /**
     * Choosing translations' file
     */

    if (language.equals("GB")) {
        language = "en";
    } else {
        language = "fr";
    }

    String translations = path
            + "WEB-INF/classes/commonComponents/ApplicationResources_"
            + language + ".properties";

    FileInputStream fis = new FileInputStream(translations);
    ResourceBundle messages = new PropertyResourceBundle(fis);

    /**
     * Retrieving date
     */

    Date today = new Date();
    DateFormat dateFormatter = DateFormat
            .getDateInstance(DateFormat.DEFAULT);
    String dateOut = dateFormatter.format(today);
    DateFormat timeFormatter = DateFormat
            .getTimeInstance(DateFormat.DEFAULT);
    String timeOut = timeFormatter.format(today);

    /**
     * Filling title and date
     */

    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("Title", messages.getString(title));
    parameters.put("Generation", " " + dateOut + " " + timeOut);

    /**
     * Filling headers
     */

    int a;
    for (a = 1; a < headers.length; a++) {
        parameters.put("Parameter_" + a,
                messages.getString("field." + headers[a] + "_short"));
    }

    /**
     * Populating with data
     */

    List list = new ArrayList();
    Bean line = null;
    LinkedHashMap<String, Object> hmap = null;

    int j, i;

    for (j = 0; j < data.length; j++) {
        hmap = (LinkedHashMap<String, Object>) data[j];
        line = new Bean();

        for (i = 1; i < headers.length; i++) {
            line.choosefield(i, headers, hmap);
        }
        list.add(line);
    }

    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,
            parameters, new JRBeanCollectionDataSource(list));

    /**
     * Random filename generator
     */

    String filename = String.format("%s",
            RandomStringUtils.randomAlphabetic(10));

    /**
     * Exporting
     */

    // if (type.equals("pdf")) {

    JasperExportManager.exportReportToPdfFile(jasperPrint, path + filename
            + ".pdf");
    // } else if (type.equals("excel")) {

    JRXlsExporter exporterXLS = new JRXlsExporter();
    exporterXLS.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
    exporterXLS.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, path
            + filename + ".xls");

    exporterXLS.exportReport();
    // }

    // else {
    // System.out.println("Invalid file type.");
    // }

    final long duration = System.nanoTime() - startTime;
    System.out.println(duration);

    System.out.println("The report has been generated!");
    return filename;
}

I’m a bit confused with how to do it but I started like this

public class StreamingExportReportServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    String dataStr = req.getParameter("data");

    // Converts JSON into Map

    Map responseMap = new ObjectMapper().readValue(dataStr, Map.class);

    // Gets title, headers and data
    String type = (String) responseMap.get("type");
    String language = (String) responseMap.get("language");
    String template = (String) responseMap.get("template");
    String title = (String) responseMap.get("title");
    List<Map> headers = (List<Map>) responseMap.get("headers");
    Object[] rows = (Object[]) responseMap.get("data");

    // Converts headers to str[]

    String header[] = new String[headers.size()];
    for (int j = 0; j < headers.size(); j++) {
        header[j] = (String) headers.get(j).get("name");
    ...
    }
}

I started to perform a data conversion from what I get to what my generateReport function arguments are.
Using Windows and JDK 1.6


Source: java

Leave a Reply