无法让getOutputStream()在servlet中工作

时间:2015-10-05 11:57:51

标签: java json spring jsp servlets

我正在向servlet发送一个json对象并通过一个函数调用servlet。这是我的jsp页面和功能:

    <script type="text/javascript">
function retrieveTicketsExcel(){
    var jsonData = {};
    jsonData["tower"]=$('#appTower').val();
    jsonData["sDate"]=$('#startDate').val();
    jsonData["eDate"]=$('#endDate').val();
    jsonData["apps"]=$('#appfilter').html();
    jsonData["duration"]=$('#duration').val();
    jsonData["severity"]=$('#severity').val();
    jsonData["releasetype"]=$('#releasetype').val();
    jsonData["query"]=$('#query').val();

         $.ajax
            ({
                type: "GET",
                url:"retrieveTicketsToExcel.htm",
                data:'requestData='+JSON.stringify(jsonData),
                dataType: "json",

            });
         }
</script>
    <div class="modal-footer">
              <input type="button" class="btn btn-default" value="Export" onclick="javascript:retrieveTicketsExcel();">
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>

现在我调用的是Servlet方法:

@RequestMapping(value = "/retrieveTicketsToExcel.htm", method = RequestMethod.GET)
public void retrieveTickets(@RequestParam("requestData") String requestData, HttpServletRequest request, HttpServletResponse response) throws IOException {
    // UserDAO userDAO = new UserDAO();
    // userDAO.setDataSource(dataSource);
    System.out.println("*****************/GRTBDashboard/retrieveTicketsToExcel****************");
    Map<String, String> requestMap = new Gson().fromJson(requestData, Map.class);

    response.reset();
    response.resetBuffer();

    response.setContentType("application/vnd.ms-excel");
    response.addHeader("Cache-control", "no-cache");
    response.setHeader("Content-disposition", "Attachment;filename=\"Ticket_Details.xls\"");
    ServletOutputStream fileOut = response.getOutputStream();

    System.out.println("retrieveTickets - > " + requestData);
    List<DashboardData> dashboardDataList = null;
    String tower = requestMap.get("tower");
    System.out.println(tower);
    try {
        dashboardDataList = userDAO.retrieveTickets(requestMap);
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }

    final double noOfRecords = dashboardDataList.size();
    double count = Math.ceil(noOfRecords / 30000);
    try {

        HSSFWorkbook workbook = new HSSFWorkbook();
        short dateFormat = workbook.createDataFormat().getFormat("YYYY-MM-DD HH:mm");

        Iterator<DashboardData> iterator = dashboardDataList.iterator();

        for (int i = 1; i <= count; i++) {
            int c1 = 1;
            HSSFSheet sheet = workbook.createSheet(tower);

            HSSFCellStyle style = workbook.createCellStyle();
            HSSFFont font = workbook.createFont();
            font.setFontName("Verdana");
            style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
            style.setFillPattern(style.SOLID_FOREGROUND);
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            font.setColor(HSSFColor.BLACK.index);
            style.setFont(font);
            HSSFRow header = sheet.createRow(0);
            ;

            header.createCell((short) 0).setCellValue(new HSSFRichTextString("Type"));
            header.getCell((short) 0).setCellStyle(style);

            header.createCell((short) 1).setCellValue(new HSSFRichTextString("Ticket Number"));
            header.getCell((short) 1).setCellStyle(style);

            header.createCell((short) 2).setCellValue(new HSSFRichTextString("Open Date"));
            header.getCell((short) 2).setCellStyle(style);

            header.createCell((short) 3).setCellValue(new HSSFRichTextString("Closed Date"));
            header.getCell((short) 3).setCellStyle(style);

            header.createCell((short) 4).setCellValue(new HSSFRichTextString("Reported By"));
            header.getCell((short) 4).setCellStyle(style);

            header.createCell((short) 5).setCellValue(new HSSFRichTextString("Severity"));
            header.getCell((short) 5).setCellStyle(style);

            header.createCell((short) 6).setCellValue(new HSSFRichTextString("Assigned App"));
            header.getCell((short) 6).setCellStyle(style);

            header.createCell((short) 7).setCellValue(new HSSFRichTextString("Status"));
            header.getCell((short) 7).setCellStyle(style);

            int rowIndex = 1;

            while (iterator.hasNext() && c1 <= 30000) {
                DashboardData dashboardData = iterator.next();
                System.out.println("Data : "+dashboardData.getTicketNumber());
                HSSFRow row = sheet.createRow(rowIndex++);

                HSSFCell cell0 = row.createCell((short) 0);
                cell0.setCellValue(new HSSFRichTextString(dashboardData.getType()));

                HSSFCell cell1 = row.createCell((short) 1);
                cell1.setCellValue(new HSSFRichTextString(dashboardData.getTicketNumber()));

                HSSFCell cell2 = row.createCell((short) 2);
                cell2.setCellValue(new HSSFRichTextString(dashboardData.getOpenDate().toString()));

                HSSFCell cell3 = row.createCell((short) 3);
                cell3.setCellValue(new HSSFRichTextString(dashboardData.getClosedate().toString()));

                HSSFCell cell4 = row.createCell((short) 4);
                cell4.setCellValue(new HSSFRichTextString(dashboardData.getReportedBy()));

                HSSFCell cell5 = row.createCell((short) 5);
                cell5.setCellValue(new HSSFRichTextString(dashboardData.getPriority()));

                HSSFCell cell6 = row.createCell((short) 6);
                cell6.setCellValue(new HSSFRichTextString(dashboardData.getAssignedGroup()));

                HSSFCell cell7 = row.createCell((short) 7);
                cell7.setCellValue(new HSSFRichTextString(dashboardData.getStatus()));
                c1++;

            }
            for (int autosize = 0; autosize <= 10; autosize++) {

                sheet.autoSizeColumn((short) autosize);
            }

        }

        workbook.write(fileOut);
    } catch (FileNotFoundException e2) {
        e2.printStackTrace();
    } finally {
        if (null != fileOut)
            fileOut.close();
    }
    fileOut.close();
    fileOut.flush();
}

我正在尝试将数据清除为我正在编写的excel,但是点击导出按钮除了在jsp页面上提供下载外。 如果我正在尝试使用FileOutputStream()进行书写,那么它在我的光盘上写得非常完美。但我想在jsp页面中使用response.getOutputStream()进行下载。

1 个答案:

答案 0 :(得分:0)

也许问题出在JQuery方面?

您可以通过在浏览器中手动打开retrieveTicketsToExcel.htm来获得下载吗?如果是这样,那么尝试使用window.location.href="retrieveTicketsToExcel.htm"而不是JQuery的ajax();

编辑: 我现在很确定问题出在Query端。首先,ajax请求无法启动文件下载对话框。 window.location.href或提交表格是您的选择。

此外,您在ajax调用中提供json作为dataType。这是错误的,因为dataType指定了您期望从服务器返回的数据类型,而不是您发送的请求的格式(http://api.jquery.com/jquery.ajax/

EDIT2:

您对data:'requestData='+JSON.stringify(jsonData)的使用也存在问题。您不能简单地将JSON字符串附加到网址。您需要先对其进行编码。尝试使用 data:'requestData='+ encodeURI(JSON.stringify(jsonData))

或者更好的是,使用POST请求,因为这似乎在语义上更正确。这样你就不需要requestData=部分,但也需要稍微更改servlet代码。您需要直接从Servlet inputStream或reader中读取json。

这样的事情: new Gson().fromJson(request.getReader(), Map.class);;