Why does JasperViewer only works on localhost?

2019-01-28 19:12发布

问题:

I was just wondering why JasperViewer only works on localhost. When I deployed my project to server, clients can not be able to view the reports anymore.

String reportDir = getServletContext().getRealPath("WEB-INF/classes/com/proj/reports");
        String fileName = reportDir + "\\" + request.getParameter("reportName") + ".jasper";
        File outReportDir = new File("C:/REPORTS_FOLDER");
        outReportDir.mkdir();
        long millis = System.currentTimeMillis();
        String outFileName = outReportDir + "\\" + request.getParameter("reportName") + "_" + millis + ".pdf";
        HashMap parameters = new HashMap();
        parameters.put("P_BOOKING_MONTH", request.getParameter("selMonth"));
        parameters.put("P_BOOKING_YR", request.getParameter("selYear"));

        try {
            Connection conn = ConnectionUtil.getConnection();
            JasperPrint print = JasperFillManager.fillReport(fileName, parameters, conn);
            JRExporter exporter = new net.sf.jasperreports.engine.export.JRPdfExporter();
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, outFileName);
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
            exporter.exportReport();

            JasperViewer.viewReport(print, false); }...

回答1:

JasperViewer is a swing component it is launched on the computer that executes the command (normally used in installed applications), hence if you execute the command on server it will open on server (or throw a HeadlessException, if not configured to have a screen), conclusion we can't use this command in our server application.

You could use an applet to launch the command on client computer but I strongly recommend not to use this (its support in browser is decreasing, so you can't be sure that it's working for all clients)

Normally what is done instead is that an export to pdf (html or other format of choice) is sent to client browser, client can open file with favorite program and preview it.

In your example code you are already exporting to pdf, pass the pdf directly to client. Hence remove

JasperViewer.viewReport(print, false);


回答2:

You have hard-coded the output directory in the source code.

There could always be issues like the server is not a Windows environment or the folder "C:/REPORTS_FOLDER" is not there in the server.

It would be better to have it as a configurable property.