JSF页面中导出txt文件

使用JSF和Servlet实现TXT文件导出功能
本文详细介绍了如何使用JSF和Servlet在Web应用中将数据导出为TXT文件,包括设置响应类型、添加下载提示、编写数据到TXT的操作。
/**
* 导出txt文件
*/
public void exportTxt() {
HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
writeToTxt(httpServletResponse);
FacesContext.getCurrentInstance().responseComplete();
}

/**
* 写入数据到txt
* @param response
*/
public void writeToTxt(HttpServletResponse response) {

response.setContentType("text/plain");// 以纯文本的形式发送。
response.addHeader("Content-Disposition",
"attachment;filename=data.txt");// filename指定默认的名字
BufferedOutputStream buff = null;
StringBuffer write = new StringBuffer();
String tab = ",";
String enter = "\r\n";
ServletOutputStream outSTr = null;
try {
outSTr = response.getOutputStream();
buff = new BufferedOutputStream(outSTr);
write.append("测试数据1" + tab);
write.append("测试数据2" + tab);
write.append("测试数据3" + tab);
write.append("测试数据4" + tab);
write.append("测试数据5" + tab);
write.append("测试数据6");
write.append(enter);
write.append("测试数据1" + tab);
write.append("测试数据2" + tab);
write.append("测试数据3" + tab);
write.append("测试数据4" + tab);
write.append("测试数据5" + tab);
write.append("测试数据6");
write.append(enter);

buff.write(write.toString().getBytes("UTF-8"));
buff.flush();
buff.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
buff.close();
outSTr.close();
} catch (Exception e) {
e.printStackTrace();
}
}

}

//页面调用
<h:commandButton action="#{exportAction.exportTxt}" value="保存数据" />
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值