从JSF应用程序的任何Web浏览器强制保存对话框

我已经创build了一个JSF应用程序,并且我想在页面中embedded一个链接,当点击这个链接时,后台bean将释放一些xml,并强制打开一个“另存为”下载对话框,以便用户可以select一个位置保存文件。 我已经写了JAXB代码。

这是怎么做的?

谢谢

将HTTP Content-Disposition标头设置为attachment 。 这将popup另存为对话框。 你可以使用HttpServletResponse#setHeader()来做到这一点。 您可以通过ExternalContext#getResponse()从JSF引擎中获得HTTP servlet响应。

在JSF上下文中,你只需要确保你事后调用FacesContext#responseComplete()来避免IllegalStateException的飞行。

开球的例子:

 public void download() throws IOException { FacesContext facesContext = FacesContext.getCurrentInstance(); ExternalContext externalContext = facesContext.getExternalContext(); HttpServletResponse response = (HttpServletResponse) externalContext.getResponse(); response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide. response.setContentType("application/xml"); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename. response.setHeader("Content-disposition", "attachment; filename=\"name.xml\""); // The Save As popup magic is done here. You can give it any filename you want, this only won't work in MSIE, it will use current request URL as filename instead. BufferedInputStream input = null; BufferedOutputStream output = null; try { input = new BufferedInputStream(getYourXmlAsInputStream()); output = new BufferedOutputStream(response.getOutputStream()); byte[] buffer = new byte[10240]; for (int length; (length = input.read(buffer)) > 0;) { output.write(buffer, 0, length); } } finally { close(output); close(input); } facesContext.responseComplete(); // Important! Else JSF will attempt to render the response which obviously will fail since it's already written with a file and closed. } 

使用content-disposition: attachment HTTP标头

有时你需要强制编写者通过调用response.getWriter().flush();来将内容发送给客户端response.getWriter().flush(); 在closures作家之前。 这在我的情况下提示保存为popup。