I'm following this guide in order to compile and create a PDF using struts2 jasper reports plugin but I have to load the report.jrxml
from a different path than WEB_APP/report.jrxml.
This is my action result:
<action name="jasper" class="web.app.controller.JasperAction">
<result name="success" type="jasper">
<param name="location">${location}</param>
<param name="dataSource">map</param>
<param name="format">PDF</param>
</result>
</action>
where ${location} == /my/absolute/path
.
ofcourse I receive this error:
javax.servlet.ServletException: java.io.FileNotFoundException: WEB_APP/my/absolute/path/report.jasper
How can I change the "base path"? Should I configure better this dependency?
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>${jasperreports.version}</version>
<type>jar</type>
<scope>compile</scope>
<exclusions>
<exclusion>
<artifactId>commons-collections</artifactId>
<groupId>commons-collections</groupId>
</exclusion>
</exclusions>
</dependency>
I've found the solution, and here is the code I've implemented (I've omitted the data source part because I think is useless for the example):
ACTION CLASS
public class JasperAction extends ActionSupport implements ServletContextAware {
private static final Logger LOG = LogManager.getLogger(JasperAction.class);
private ServletContext servletContext;
private String location = "report.jasper";
@Override
public String execute() throws Exception {
String jrxmlPath = "/my/path/to/report.jrxml";
String jasperPath = servletContext.getRealPath("") + File.separator + location;
try {
JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);
} catch (Exception e) {
LOG.error(e);
return ERROR;
}
return SUCCESS;
}
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
struts.xml
<action name="jasper" class="web.bkgd.simba.controller.JasperAction">
<result name="success" type="jasper">
<param name="location">${location}</param>
<param name="format">PDF</param>
</result>
</action>
With this solution I can get my .jrxml files from a specific directory in my server where a user can upload the file without deploying every time the application (in my case this is very usefull since "report.jrxml" may be different in each production server where the application is deployed and may be changed over time).