Search code examples
javaservletsjasper-reportspdf-generation

Invoking a servlet from a java class


I've made (or at least tried to make) a servlet that converts a JasperPrint object to PDF and also opens this PDF in a new tab. But it seems like my code invoker is not invoking my servlet and also it's not throwing any exception.

When I call the URL directly from the browser, it does call the servlet, but the same doesn't happen from my java class.

Invoker Code:

URL url = new URL("http://localhost:8080/app/reportgenerator");
HttpURLConnection connection =  (HttpURLConnection)url.openConnection(); 

connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setDefaultUseCaches (false);
connection.setRequestProperty("Content-Type", "application/octet-stream");

ObjectOutputStream out = new ObjectOutputStream(connection.getOutputStream());
JasperPrint jasperPrint = new JasperPrint();
out.writeObject(jasperPrint);           
out.close();

Servlet Code:

response.setContentType("application/pdf");
response.setHeader("Content-Disposition","attachment; filename=\"report.pdf\"");

JasperPrint jasperPrint = null;

try {
    ObjectInputStream resultStream = new ObjectInputStream(request.getInputStream());
    jasperPrint = (JasperPrint) resultStream.readObject();
    resultStream.close();

    JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());

What am I doing wrong?


Solution

  • I found the solution after a lot more research. That was how I've solved my problem: Calling a Servlet from a Java application