【问题标题】:Not able to get getOutputStream() working in servlet无法让 getOutputStream() 在 servlet 中工作
【发布时间】:2016-01-02 01:52:40
【问题描述】:

我正在向 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() 进行写入,它会在我的光盘上完美写入。但是我想用response.getOutputStream()在jsp页面下载。

【问题讨论】:

  • 你有错误显示吗?由于在 finally 中关闭后关闭和刷新,这可能是一个例外
  • 我没有收到任何错误。我什至尝试删除 finally 块,但没有用
  • 点击按钮时发生了什么?你甚至知道你的控制器的方法是否真的被调用了吗?
  • 一些想法:尝试重新抛出异常而不是调用 printStackTrace (throw new RuntimeException("some error", e);)。如果标准错误在网络服务器中重定向错误,您将错过错误尝试调试服务器使用 Chrome 中的开发者控制台跟踪网络调用
  • 肯定会调用控制器方法,因为如果我使用FileOutputStream,我可以编写,但如果我使用response.getOutput(),则不会发生任何事情

标签: java json spring jsp servlets


【解决方案1】:

也许问题出在 JQuery 方面?

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

编辑: 我现在很确定问题出在查询方面。首先,ajax 请求不能启动文件下载对话框。 window.location.href 或提交表单是您的选择。

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

编辑2:

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

或者更好的是,使用 POST 请求,因为这在语义上看起来更正确。这样您就不需要requestData= 部分,但还必须稍微更改一下servlet 代码。您需要直接从 Servlet inputStream 或阅读器中读取 json。

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

【讨论】:

  • window.location.href="retrieveTicketsToExcel.htm" 给我找不到页面。
  • 哎呀,你应该使用window.location.href="/retrieveTicketsToExcel.htm";
  • 我都试过了,但得到了The request sent by the client was syntactically incorrect ().
  • 如果要将 JSON 附加到 url,则需要先对其进行编码。我修改了我的答案,那里有更多细节。
猜你喜欢
  • 2016-06-19
  • 2012-10-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
  • 1970-01-01
  • 2018-02-26
  • 2019-07-06
  • 2015-11-27
相关资源
最近更新 更多