我不知道如何下载CSV文件。 CSV将在运行时生成。我需要首先将文件保存在tomcat WEB-INF目录中吗? 我正在使用JSF 1.2。
顺便问一下,这种任务的首选JSF组件是什么?
主要bean:
顺便问一下,这种任务的首选JSF组件是什么?
编辑 (05.05.2012 - 15:53)
我尝试了BalusC
在他的第一个链接中提到的解决方案,但是如果我点击我的commandButton,则文件的内容会显示在网页上。也许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>
,现在它可以运行了!
PrimeFaces
,因为他们从PrimeFaces 2.0
开始就不支持JSF 1.2了,这是对的吗? - yves.beutlerExternalContext#getResponse()
获取原始的HttpServletResponse
,然后调用其getOutputStream()
方法即可,但这已经在第一个链接中概述了。或者,当然,升级到JSF 2。它比JSF 1.2提供了许多优势。 - BalusCa4j:components
,它就不会工作,但现在我改用<h:commandButton>
,它可以正常工作。感谢BalusC提供的又一个好答案! - yves.beutler