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?

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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...