我不知道如何下載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)沒有正確解釋它。 –