springmvc下实现用mybatis从数据库读取数据再下载到txt文件

之前准备采用ajax的方式下载txt文件的,但是发现网页直接打开可以打开的txt文件,所以只能采用比较原始的方式了,下面直接贴核心代码部分:

<div class="layui-btn-group demoTable" style="float: left">
    <a href="download/txt" class="layui-btn" style="margin-left: 10px!important;">导出txt文档</a>
</div>

以上就是前段核心部分,直接点击超链接进入controller层,下面贴出controller层代码:

@Controller
@RequestMapping("/download")
public class downloadController {


    @Resource
    private ItemsService itemsService;

    @RequestMapping(value="/txt",method = RequestMethod.GET)
    @ResponseBody
    public void queryAccount(HttpServletRequest req,HttpServletResponse resp) throws IOException {

        itemsService.download100Avaliable(req,resp);
    }
}

下面贴出业务层代码:

@Override
@Transactional(propagation = Propagation.REQUIRED,isolation= Isolation.DEFAULT,rollbackFor=Exception.class)
public void download100Avaliable(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    ResponseData rd=new ResponseData();
    List<Account> objectList;
   /* BufferedWriter out=null;*/
    ServletOutputStream outSTr = resp.getOutputStream();// 建立;
    BufferedOutputStream buff = null;
    try{
        objectList=queryResultMapper.download100Avaliable();//先导出,实际为查询前100条记录
        //另外,还需要删除这100个记录
        queryResultMapper.delete100Avaliable();//再删除前100条记录
        //拼凑字符串
        StringBuilder content=new StringBuilder();
        for(Account object:objectList){
            content.append(object.get_account_account());
            content.append(",");
            content.append(object.get_password());
            content.append(System.getProperty("line.separator"));//换行
        }
        SimpleDateFormat sFormat=new SimpleDateFormat("yyyy-MM-dd HHmmss");
        Calendar calendar=Calendar.getInstance();
        String fileName=sFormat.format(calendar.getTime());
        resp.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".txt");
        resp.setContentType("text/plain");
        buff = new BufferedOutputStream(outSTr);
        buff.write(content.toString().getBytes(StandardCharsets.UTF_8));
        buff.flush();
        buff.close();
    }catch (Exception ex){
        ex.printStackTrace();
    }finally {
        try {
            buff.close();
            outSTr.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值