简体   繁体   中英

Not able to get getOutputStream() working in servlet

I am sending a json object to servlet and calling servlet through a function. Here is my jsp page and function:

    <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>

Now i am calling Servlet method which is:

@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();
}

I am trying to flush out data as excel which i am writing but on clicking export button does all but giving download on jsp page. If i am trying to write using FileOutputStream() it is writing perfectly on my disc. But i want to use response.getOutputStream() to download in jsp page.

Perhaps the problem is in the JQuery side?

Can you get the download working by opening retrieveTicketsToExcel.htm manually in the browser? If so, then try using window.location.href="retrieveTicketsToExcel.htm" instead of JQuery's ajax();

Edit: I am now quite sure the problem is in the Query side. First of all, ajax requests can not initiate file download dialogs. window.location.href or submitting a form are your options here.

Also, you are providing json as a dataType in your ajax call. This is wrong because dataType specifies the type of data that you're expecting back from the server, not the format of the request you're sending ( http://api.jquery.com/jquery.ajax/ )

Edit2:

Your use of data:'requestData='+JSON.stringify(jsonData) is also problematic. You can not simply appent JSON string to an url. You need to encode it first. Try using data:'requestData='+ encodeURI(JSON.stringify(jsonData))

Or better yet, use a POST request since this seems semantically more correct. That way you would not need the requestData= part, but would also have to change the servlet code a bit. You'd need to read the json from Servlet inputStream or reader directly.

Something like this: new Gson().fromJson(request.getReader(), Map.class); ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM