为什么在浏览器中使用JAX-RS和标准servlet时没有显示popup窗口?

当我尝试使用standard servlet approach ,在我的浏览器中popup窗口显示询问是否打开.xls文件或保存它。

我通过JAX-RS尝试了完全相同的代码,并且浏览器popup窗口不会以某种方式显示出来。 有没有人遇到过这个?

JAX-RS的方式,不会显示popup:

 @Path("excellaTest") public class ExcellaTestResource { @Context private UriInfo context; @Context private HttpServletResponse response; @Context private HttpServletRequest request; public ExcellaTestResource() { } @Path("horizontalProcess") @GET //@Produces("application/vnd.ms-excel") @Produces("application/vnd.ms-excel") public void getProcessHorizontally() { try { URL templateFileUrl = this.getClass().getResource("myExcelTemplate.xls"); String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8"); String outputFileDir = "MasatoExcelHorizontalOutput"; ReportProcessor reportProcessor = new ReportProcessor(); ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE); ReportSheet outputSheet = new ReportSheet("myExcelSheet"); outputBook.addReportSheet(outputSheet); reportProcessor.addReportBookExporter(new OutputStreamExporter(response)); reportProcessor.process(outputBook); System.out.println("done!!"); } catch(Exception e) { System.out.println(e); } return; } }//end class class OutputStreamExporter extends ReportBookExporter { private HttpServletResponse response; public OutputStreamExporter(HttpServletResponse response) { this.response = response; } //ReportProcessor output() //This method is call when ReportProcessor process() is invoked. //The Workbook from POI API can be used to write to stream @Override public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException { //TODO write to stream try { response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls"); book.write(response.getOutputStream()); response.getOutputStream().close(); System.out.println("booya!!"); } catch(Exception e) { System.out.println(e); } } }//end class 

你使用的是什么JAX-RS框架?

我的猜测是你的代码不起作用,因为你返回void。 您正在使用的框架可能会识别为HTTP 204无内容。 这会导致浏览器跳过实际的响应正文并忽略内容处置标题。

因为我已经写了一个并行线程:尝试返回Response对象。 您可以将OutputStream或者byte []作为实体来设置content-disposition标头。

我从来没有使用jax-rs服务的类级别注入。 我build议2个解决scheme之一。

1)尝试注入请求和响应作为方法参数。

2)输出你的文件到一个字节数组的输出stream,并从你的方法返回一个字节数组而不是void。