微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 使用JSF下载CSV文件

我不知道如何下载CSV文件. CSV将在运行时生成.我是否需要先将文件保存在tomcat WEB-INF目录中?我正在使用JSF 1.2.

顺便说一下,这种任务最受欢迎的JSF组件是什么?

编辑(05.05.2012 – 15:53)

我尝试了BalusC在他的第一个link中说明的解决方案,但如果我点击我的commandButton,该文件内容显示在网页上.也许mimetype存在问题?

XHTML文件

主豆:

    public String doDataExport() {

    try {
        export.downloadFile();  
    } catch (SurveyException e) {
        hasErrors = true;
    }
    return "";
}

出口豆类:

public void downloadFile() throws SurveyException {

    try {

        String filename = "analysis.csv";

        FacesContext fc = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

        response.reset();
        response.setContentType("text/comma-separated-values");
        response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");

        OutputStream output = response.getOutputStream();

        // writing just sample data
        List

编辑(05.05.2012 – 16:27)

我解决了我的问题.我必须使用< h:commandButton>而不是< a4j:commandButton>现在它有效!

最佳答案

Do I need to save the file in the tomcat WEB-INF directory first?

不,只需在通过ExternalContext#getResponseOutputStream()获取后直接将其写入HTTP响应主体,然后设置正确的响应标头,告诉浏览器它将检索什么.

根据以下答案中的具体示例进行数学计算:

> How to provide a file download from a JSF backing bean?
> JSP generating Excel spreadsheet (XLS) to download

基本上:

ListSEOutputStream());

By the way,what’s the favorite jsf-component for this kind of task?

这是主观的.但无论如何,我们使用完全满意.

原文地址:https://www.jb51.cc/java/438084.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐