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

vol*_*vox 11 java jsf

我已经创建了一个JSF应用程序,我想在一个页面中嵌入一个链接,当点击它时会导致支持bean编组一些xm​​l并强制打开另存为下载对话框,以便用户可以选择一个位置保存文件.我已经编写了JAXB代码.

这是怎么做到的?

谢谢

Bal*_*usC 33

将HTTP Content-Disposition标头设置为attachment.这将弹出另存为对话框.你可以使用HttpServletResponse#setHeader().您可以通过JSF引擎获取HTTP servlet响应ExternalContext#getResponse().

在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.
}
Run Code Online (Sandbox Code Playgroud)