How to Pass Parameter from Java to Jasper Report

Last modified date

A frequently asked question by many beginners who are working with Jasper Reports, believe me guys I was one of you who stuck with this question, don’t know how to Google it. But finally when I found the solution I felt like it’s so simple and I want to share this with all you people.

Before getting into more details I want you guys must have basic knowledge of Jasper report designing and basic idea of creating parameters.

How to create parameters in Jasper Report

Go to jasper design click on Outline you will find Parameters, right-click on it Create Parameter, leave the class to String by Default, and name your parameter as you like. So let’s assume you have created 2 parameters naming phone and email.

Drag the phone and email from parameters and drop them in your jasper where you want to display them. When we drop the parameter in the report they look like $P(phone) and  $P(email). For safe side test them by clicking on preview and pass the parameter within the jasper report. If the report is successfully working then you are done with the report.

How to Send Parameter from Java to Jasper Report

To make it simpler I have already written the code, don’t worry I going to explain everything in detail.

connection=ConnectionManager.getConnection();
    try {
      JasperDesign jd =JRXmlLoader.load(new File("")
      .getAbsolutePath()+"/src/myjasper.jrxml");
      
        HashMap params = new HashMap();
        params.put("phone", "9123456789");
        params.put("email", "intactabode@gmail.com");
        
        
        JRDesignQuery  newQuery=new JRDesignQuery();
        newQuery.setText("select * from table");
        jd.setQuery(newQuery);
        JasperReport jr=JasperCompileManager.compileReport(jd);
        JasperPrint jp=JasperFillManager.fillReport(jr,params, connection);
        JasperPrintManager.printReport(jp, false);
      
    } catch (Exception e) {
      // TODO: handle exception
      e.printStackTrace();
    }



Important things you must remember before passing parameter to Jasper reports

  1. You must have an active database.
  2. You must provide the connection between Java and Jasper.
  3. You must pass a valid query to Jasper report.
  4. You must provide the absolute path of you jasper.
  5. You must pass parameters through Hashmap, the key must be same as your parameter name in jasper report (remember its case sensitive) and the value is your String.

It is recommended  you must have active database and pass valid query to your jasper report, if not the report show empty at jasper report compile time. Good Luck…

intactabode