как исправить нулевой сеанс при загрузке первой страницы - PullRequest
0 голосов
/ 03 ноября 2019

Я создаю сервлет, который может генерировать PDF-файл, используя идентификатор paramiter, значение которого отправляется с помощью ajax. В сервлете я создаю сеанс, когда страница, запущенная для первого сеанса, все еще пуста, когда я нажимаю второй раз, он дает мне значение первого щелчка

$('.table tbody').on('click', '.btn-pdf', function (event) {
                event.preventDefault();
                var currow = $(this).closest('tr');
                var id = currow.find('td:eq(0)').text();
                $.ajax({
                    type: "POST",
                    data: {
                        reqId: id
                    },
                    url: "${pageContext.request.contextPath}/CreerPdfServlet",
                    success: function () {
                        //Pour recuper la largeur de l'ecran
                        var viewportHeight = $(window).height();
                        //Pour calculer la hauteur de l'ecran
                        var viewportWidth = $(window).width();
                        if (viewportWidth >= 1250) {
                            $("#dialog").show().kendoWindow({
                                width: 1250,
                                height: Math.ceil(viewportHeight * 100 / 100),
                                modal: true,
                                title: "Fichier pdf"
                            });
                        } else {
                            $("#dialog").show().kendoWindow({
                                width: viewportWidth,
                                height: Math.ceil(viewportHeight * 100 / 100),
                                modal: true,
                                title: "Fichier pdf"
                            });
                        }
                        $("#loader").load(window.location.href+"#loader");
                    }
                });
            });
<div id="dialog" style="display:none" class="embed-responsive">
 
<%
    String fileName =(String) session.getAttribute("fileName"); 
%>
                    <iframe class="embed-responsive-item"
                            src="../AppData/<%=fileName%>"
                            ></iframe>
 </div>
protected void processRequest (запрос HttpServletRequest, ответ HttpServletResponse) выдает ServletException, IOException {response.setContentType ("text / html; charset = UTF-8");HttpSession session = request.getSession ();Документ док;Автомашина v = ноль;Таблица PdfPTable;Ячейка PdfPCell;String pathApp = "";Строка file_name = "";
    try (PrintWriter out = response.getWriter()) {
        try {
            String nom = session.getAttribute("nom").toString();
            int id = Integer.parseInt(request.getParameter("reqId"));

            pathApp = request.getServletContext().getRealPath("/AppData").replace("build", "")
                    + File.separator + nom;
            file_name = "doc_" + genRandom() + ".pdf";
            File file = new File(pathApp);
            if (!file.exists()) {
                file.mkdir();
            }
            String path = pathApp + File.separator + file_name;
            doc = new Document();
            PdfWriter.getInstance(doc, new FileOutputStream(path));
            //L'entete du document
            doc.addCreationDate();
            doc.setPageSize(PageSize.LETTER);
            doc.open();

            //Creation des fonts de style
            Font bfBold18 = new Font(FontFamily.TIMES_ROMAN, 18, Font.BOLD, new BaseColor(0, 0, 0));
            Font bfBold12 = new Font(FontFamily.TIMES_ROMAN, 12, Font.BOLDITALIC, new BaseColor(0, 0, 0));
            Font bf12 = new Font(FontFamily.TIMES_ROMAN, 12);
            Font fontContent = new Font(FontFamily.TIMES_ROMAN, 12, Font.NORMAL);

            table = new PdfPTable(1);
            float[] widths = new float[]{800f};
            table.setWidthPercentage(widths, doc.getPageSize());
            table.setSpacingBefore(0f);
            table.setSpacingAfter(10f);
            table.setWidthPercentage(100);

            // L'entete du fiche
            cell = new PdfPCell(new Paragraph("Fiche d'enregistrement des voitures", bfBold18));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBorder(0);
            table.addCell(cell);
            doc.add(table);

            //Nouveau table les champs
            table = new PdfPTable(2);
            widths = new float[]{50f, 50f};
            table.setWidthPercentage(widths, doc.getPageSize());
            table.setSpacingBefore(30f);
            table.setSpacingAfter(40f);
            table.setWidthPercentage(100);

            List<Vehicule> list = Vehicule.ListVehiculeById(id);
            if (list != null && list.size() > 0) {
                v = list.get(0);

                cell = new PdfPCell(new Paragraph("Information du propriataire", bfBold12));
                cell.setColspan(2);
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setBorder(0);
                table.addCell(cell);
                ////////////////////////
                cell = new PdfPCell(new Paragraph("Nom complet :", fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph(v.getNom() + " " + v.getPrenom(), fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                /////////////////////////
                cell = new PdfPCell(new Paragraph("Sexe :", fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph(v.getSexe(), fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph("Adresse :", fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph(v.getAdresse(), fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                /////////////////////////
                cell = new PdfPCell(new Paragraph("Telephone :", fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph(v.getTel(), fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                ///////////////////
                cell = new PdfPCell(new Paragraph("NIF/CIN :", fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph(v.getCin_nif(), fontContent));
                cell.setBorder(0);
                table.addCell(cell);

                ////spacing
                cell = new PdfPCell(new Paragraph(""));
                cell.setColspan(2);
                cell.setBorder(0);
                table.addCell(cell);
                ////
                cell = new PdfPCell(new Paragraph("Information du voiture", bfBold12));
                cell.setColspan(2);
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                cell.setBorder(0);
                table.addCell(cell);
                ////////////////////////
                cell = new PdfPCell(new Paragraph("Type voiture :", fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph(v.getType(), fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                /////////////////////////
                cell = new PdfPCell(new Paragraph("No moteur :", fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph(v.getNo_moteur(), fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                /////////////////////
                cell = new PdfPCell(new Paragraph("Marque :", fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph(v.getMarque(), fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                ///////////////////
                cell = new PdfPCell(new Paragraph("No serie :", fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph(v.getNo_serie(), fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                //////////////////////
                cell = new PdfPCell(new Paragraph("Couleur :", fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph(v.getCouleur(), fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                /////////////////////
                cell = new PdfPCell(new Paragraph("Model :", fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph(v.getModel(), fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                ///////////////////
                cell = new PdfPCell(new Paragraph("Nombre roue :", fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph("" + v.getNo_serie(), fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                //////////////////
                cell = new PdfPCell(new Paragraph("Nombre cylindre :", fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph("" + v.getNbre_cylindre(), fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                /////////////////
                cell = new PdfPCell(new Paragraph("Type de caburant :", fontContent));
                cell.setBorder(0);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph(v.getType_carburant(), fontContent));
                cell.setBorder(0);
                table.addCell(cell);

                doc.add(table);
                //doc.add(para);
            }
            doc.close();
          out.print(file_name);
        } catch (Exception e) {

        }

        // ServletContext context = request.getServletContext();

        session.setAttribute("fileName", file_name);

    }
}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...