Step 1: Learn Java
If you already know Java, great! If you're familiar with programming, something like this tutorial will probably be enough to get you started.
Step 2: Code
There are two different methods (not mutually exclusive) for creating scriptlets. One is to piggyback on the default scriptlet class provided by Jaspersoft. The methods within this class correspond to events within report processing, and they will run automatically with the report you attach the scriptlet to.
The second strategy is to create your own methods using any existing Java functionality (part 2 covers java.sql.*). You have to call these specifically from the report if you want them to run.
Either way you go, you need to do the following:
- Create your .java code file. The file name must match your class name (so FileName.java must contain public class FileName ...)
- Include the external classes you need in your file. For example:
- Create your program.
Jasperserver comes with a compiler (located in <Jasper Home>\java\bin), so it's easiest just to use that. It's even easier if you add this to your system path variable so you can call javac from anywhere. If you want to use the standard JDK, that is fine, but there will be problems if you try to run the report on a server with a prior version of java from what you developed in.
To use Jasperserver-specific classes (as in the example above) you need to include the Jasper Reports library when you run javac. For example:
javac -classpath "C:\Program Files\jasperserver-ce-3.7.1\apache-tomcat\webapps\jasperserver\WEB-INF\lib\jasperreports-184.108.40.206.jar" FileName.java
Step 4: Create the JAR
Once you have compiled your code successfully, you can create the jar file with a simple command:
jar cvf JarFileName.jar FileName.java FileName.class
Step 5: Add Scriptlet to Report
First, add your jar file to the iReport classpath (Tools>Options>Classpath>Add JAR).
Once you've done this, just go to your (iReport) report inspector, right-click 'Scriptlets' and 'Add Scriptlet'. If you are only extending the default jasper scriptlet class, that's all you have to do - just compile your report and run it.
If you want to call your own method(s) within the report, you'll need to change the scriptlet class in your report properties to match your scriptlet rather than the default. You can then call the method from a text field using something like this:
Once you are ready to run this from Jasperserver, you'll need to upload the jar file as a resource when you create the report.
That's it! In part 2, we'll look at a specific scriptlet that uses all of this to write back to the database based on information contained within the report.