栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

将HTTP

Content-Disposition
标头设置为
attachment
。这将弹出一个 另存为
对话框。您可以使用进行操作
HttpServletResponse#setHeader()
。您可以通过JSF幕后获得HTTP
servlet响应
ExternalContext#getResponse()


在JSF上下文中,只需要确保

FacesContext#responseComplete()
稍后再调用即可避免
IllegalStateException
s飞散。

开球示例:

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.}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/449599.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号