Java Restful API返回带有Jasper的PDF文件
我有一个Restful API(JAX-RS),需要使用JasperReport库返回一个PDF文件 但当我在浏览器中运行URL时,Jasper生成方法在FacesContext.getCurrentInstance().getExternalContext()行中给出null。我可以通过HttpServletRequest捕获外部上下文吗 有人能帮我吗 吼我的“RestClass”Java Restful API返回带有Jasper的PDF文件,java,jasper-reports,restful-url,Java,Jasper Reports,Restful Url,我有一个Restful API(JAX-RS),需要使用JasperReport库返回一个PDF文件 但当我在浏览器中运行URL时,Jasper生成方法在FacesContext.getCurrentInstance().getExternalContext()行中给出null。我可以通过HttpServletRequest捕获外部上下文吗 有人能帮我吗 吼我的“RestClass” @Path(“/Integracao”) 公共类集成{ @得到 @路径(“/teste”) 公共无效测试(){
@Path(“/Integracao”)
公共类集成{
@得到
@路径(“/teste”)
公共无效测试(){
TrCboServiceImpl cS=新的TrCboServiceImpl();
列表数据源=null;
试一试{
datasource=cS.listAll();
}捕获(服务异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
AbstractApplicationBean aab=新的AbstractApplicationBean(){
@凌驾
公共布尔值UseMultipResaService(){
返回false;
}
};
试一试{
gerarJasper(“RelTrCbo”,TipoRelatorioEnum.PDF.getType(),datasource,newhashmap());
}捕获(例外e){
e、 printStackTrace();
}
}
}
还有我的发电机jasper
public void gerarJasper(String name, String type, List data, Map params) throws IllegalArgumentException, RuntimeException, Exception {
boolean found = false;
for (int i = 0; i < VALID_TYPES.length; i++) {
if (VALID_TYPES[i].equals(type)) {
found = true;
break;
}
}
if (!found) {
throw new IllegalArgumentException("Tipo solicitado '" + type + "' inválido");
}
// Procurar recurso de design de relatório compilado
// NullPointerException OCCURS HERE!!!
ExternalContext econtext = FacesContext.getCurrentInstance().getExternalContext();
InputStream stream = econtext.getResourceAsStream(PREFIX + name + SUFFIX);
if (stream == null) {
throw new IllegalArgumentException("O relatório '" + name + "' não existe");
}
FacesContext fc = FacesContext.getCurrentInstance();
ServletContext context = (ServletContext)fc.getExternalContext().getContext();
String path = context.getRealPath(File.separator) + "resources/jasper" + File.separator;
String logo = context.getRealPath(File.separator) + "resources/imagens" + File.separator;
params.put("SUBREPORT_DIR", path);
params.put("LOGO_DIR", logo);
JRDataSource ds = new JRBeanArrayDataSource(data.toArray());
JasperPrint jasperPrint = null;
try {
jasperPrint = JasperFillManager.fillReport(stream, params, ds);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FacesException(e);
} finally {
try {
stream.close();
} catch (IOException e) {
}
}
JRExporter exporter = null;
HttpServletResponse response = (HttpServletResponse) econtext.getResponse();
FacesContext fcontext = FacesContext.getCurrentInstance();
try {
response.setContentType(type);
if ("application/pdf".equals(type)) {
exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
} else if ("text/html".equals(type)) {
exporter = new JRHtmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, response.getWriter());
HttpServletRequest request = (HttpServletRequest) fcontext.getExternalContext().getRequest();
request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);
exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, new HashMap());
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, request.getContextPath() + "/image?image=");
}else if("application/xlsx".equals(type)){
exporter = new JRXlsxExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
}else if("application/docx".equals(type)){
exporter = new JRDocxExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
} else if("application/rtf".equals(type)){
exporter = new JRRtfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FacesException(e);
}
try {
exporter.exportReport();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FacesException(e);
}
fcontext.responseComplete();
}
public void gerarJasper(字符串名称、字符串类型、列表数据、映射参数)抛出IllegalArgumentException、RuntimeException、Exception{
布尔值=false;
for(int i=0;i
我解决了这个问题!!!
我需要在我的项目(Restful API)的lib文件夹中导入iReport、Barbake-1.5、barcode4j-2.0、jasperserver-iReport-plugin-2.0.1、jdt-compiler-3.1.1 JAR
在我的代码下面
@Path("/Integracao")
public class Integracao {
@Context
private HttpServletRequest httpServletRequest;
@GET
@Path("/gerarPdf")
public Response geraPDF(@QueryParam("relatorio") String arquivoJrxml,
@QueryParam("autorizacao") String autorizacao){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Map fillParams = new HashMap();
fillParams.put("IMPRAUTORIZACAO", autorizacao);
PdfGenerator pdf = new PdfGenerator();
byte[] bytes= pdf.generateJasperReportPDF(httpServletRequest, arquivoJrxml, outputStream, fillParams);
String nomeRelatorio= arquivoJrxml + ".pdf";
return Response.ok(bytes).type("application/pdf").header("Content-Disposition", "filename=\"" + nomeRelatorio + "\"").build();
}
}
还有我的课
public class PdfGenerator {
public byte[] generateJasperReportPDF(HttpServletRequest httpServletRequest, String jasperReportName, ByteArrayOutputStream outputStream, Map parametros) {
JRPdfExporter exporter = new JRPdfExporter();
try {
String reportLocation = httpServletRequest.getRealPath("/") +"resources\\jasper\\" + jasperReportName + ".jrxml";
InputStream jrxmlInput = new FileInputStream(new File(reportLocation));
//this.getClass().getClassLoader().getResource("data.jrxml").openStream();
JasperDesign design = JRXmlLoader.load(jrxmlInput);
JasperReport jasperReport = JasperCompileManager.compileReport(design);
//System.out.println("Report compiled");
//JasperReport jasperReport = JasperCompileManager.compileReport(reportLocation);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parametros, HibernateUtils.currentSession().connection()); // datasource Service
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);
exporter.exportReport();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error in generate Report..."+e);
} finally {
}
return outputStream.toByteArray();
}
}
public class PdfGenerator {
public byte[] generateJasperReportPDF(HttpServletRequest httpServletRequest, String jasperReportName, ByteArrayOutputStream outputStream, Map parametros) {
JRPdfExporter exporter = new JRPdfExporter();
try {
String reportLocation = httpServletRequest.getRealPath("/") +"resources\\jasper\\" + jasperReportName + ".jrxml";
InputStream jrxmlInput = new FileInputStream(new File(reportLocation));
//this.getClass().getClassLoader().getResource("data.jrxml").openStream();
JasperDesign design = JRXmlLoader.load(jrxmlInput);
JasperReport jasperReport = JasperCompileManager.compileReport(design);
//System.out.println("Report compiled");
//JasperReport jasperReport = JasperCompileManager.compileReport(reportLocation);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parametros, HibernateUtils.currentSession().connection()); // datasource Service
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);
exporter.exportReport();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error in generate Report..."+e);
} finally {
}
return outputStream.toByteArray();
}
}