我不知道如何下载CSV文件。 CSV将在运行时生成。我需要先将文件保存在tomcat WEB-INF目录中吗?我正在使用JSF 1.2。使用JSF下载CSV文件
顺便说一下,这种类型的任务最受欢迎的JSF组件是什么?
编辑(05.05.2012 - 15:53)
我试图解决BalusC
在他的第一个link说,但如果我点击我的commandButton显示网页上的文件的内容。 mimetype
可能有问题吗?
XHTML文件:
<a4j:form>
<a4j:commandButton action="#{surveyEvaluationBean.doDataExport}" value="#{msg.srvExportButton}" />
</a4j:form>
主要豆:
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<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',因为他们不支持JSF 1.2,因为'PrimeFaces 2.0'当我是对的? –
这是正确的,古老的JSF 1.x即将结束,因此您不应该期望新的组件库支持它。只需手动进行流式传输即可。您只需通过'ExternalContext#getResponse()'获取原始的'HttpServletResponse',然后调用它的'getOutputStream()',但这已在第一个链接中列出。或者,当然,升级到JSF 2.它提供了比JSF 1.2更多的优势。 – BalusC
我知道jsf 1.2的缺点,但目前我们无法升级到更高级别。我试图理解你的第一个链接,但它不起作用。我使用了我在网上找到的mimetype'text /逗号分隔值',但浏览器(IE,FF,Chrome)没有正确解释它。 –