gpt4 book ai didi

java - 使用 JSF 下载 CSV 文件

转载 作者:搜寻专家 更新时间:2023-10-31 20:14:42 24 4
gpt4 key购买 nike

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

顺便问一下,最适合此类任务的 JSF 组件是什么?


编辑(2012 年 5 月 5 日 - 15:53)

我尝试了解决方案 BalusC在他的第一个 link 中陈述,但是如果我点击我的命令按钮,文件的内容就会显示在网页上。也许 mimetype 有问题?

xhtml 文件:

<a4j:form>
<a4j:commandButton action="#{surveyEvaluationBean.doDataExport}" value="#{msg.srvExportButton}" />
</a4j:form>

主 bean :

    public String doDataExport() {

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

导出 bean :

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<String> strings = new ArrayList<String>();

strings.add("filename" + ";" + "description" + "\n");
strings.add(filename + ";" + "this is just a test" + "\n");

for (String s : strings) {
output.write(s.getBytes());
}

output.flush();
output.close();

fc.responseComplete();

} catch (IOException e) {
throw new SurveyException("an error occurred");
}
}

编辑 (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 响应正文中在设置了正确的响应 header 之后,它会告诉浏览器它将要检索的内容。

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

基本上:

List<List<Object>> csv = createItSomehow();
writeCsv(csv, ';', ec.getResponseOutputStream());

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

这是主观的。但无论如何,我们正在使用 <p:dataExporter> 完全满意。

关于java - 使用 JSF 下载 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10451095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com