Questo sito utilizza cookies solo per scopi di autenticazione sul sito e nient'altro. Nessuna informazione personale viene tracciata. Leggi l'informativa sui cookies.
Username: Password: oppure
Java - Generare PDF Servlet/Jsp/Json
Forum - Java - Generare PDF Servlet/Jsp/Json

Avatar
splittik (Normal User)
Rookie


Messaggi: 27
Iscritto: 25/04/2012

Segnala al moderatore
Postato alle 23:11
Sabato, 20/08/2016
Ciao a tutti.

Ho una jsp che genera una tabella in cui l'ultima cella è un bottone che serve per raccogliere i dati della riga, passare i dati alla servel, la quale genera un document che viene scaricato in locale come pdf.

Alla pressione del bottone vengono mandati e processati i dati, ma il download non parte. Avevo implementato una versione in cui ogni riga della tabella era un form tuttavia devo usare delle datatable e quindi il mio primo approccio  funzionava ma era sbagliato.
Nei log del server non ci sono errori ...non so cosa fare

ListAutist.size è un ArrayList con il risultato di una query

Codice sorgente - presumibilmente Java

  1. for (int i = 0; i < ListAutist.size(); i++) {
  2.      beanA = (BeanAssenza) ListAutist.get(i);
  3.      out.println("<tr role='row' class='odd'><td class='sorting_1' id='Autista'>" + beanA.getAutista() + "</td>");
  4.      out.println("<td>" + beanA.getDa_ora() + "</td>");
  5.      out.println("<td>" + beanA.getDa_giorno() + "</td>");
  6.      out.println("<td>" + beanA.getA_ora() + "</td>");
  7.      out.println("<td>" + beanA.getA_giorno() + "</td>");
  8.      out.println("<td>" + beanA.getTipo_assenza() + "</td>");
  9.      out.println("<td>" + beanA.getData_dichiarazione() + "</td>");
  10.  
  11.      String nome = URLEncoder.encode(beanA.getAutista(), "UTF-8");
  12.  
  13.      out.println("<input type='hidden' name='array' value=" + nome + ">");
  14.      out.println("<input type='hidden' name='array' value=" + beanA.getDa_ora() + ">");
  15.      out.println("<input type='hidden' name='array' value=" + beanA.getDa_giorno() + ">");
  16.      out.println("<input type='hidden' name='array' value=" + beanA.getA_ora() + ">");
  17.      out.println("<input type='hidden' name='array' value=" + beanA.getA_giorno() + ">");
  18.      out.println("<input type='hidden' name='array' value=" + beanA.getTipo_assenza() + ">");
  19.      out.println("<input type='hidden' name='array' value=" + beanA.getData_dichiarazione() + ">");
  20.      int index=i+1;
  21.      out.println("<td><a href='javascript: submitform("+index+");'><i class='fa fa-download' aria-hidden='true' ></i></a></td>");



codice js
Codice sorgente - presumibilmente Delphi

  1. function submitform(i) {
  2.      $("table[id^='table']").DataTable().destroy();
  3.      var oTable = document.getElementById("tableAss");
  4.      var oCells = oTable.rows.item(i).cells;
  5.      var cellLength = oCells.length;
  6.  
  7.      var Nome = oCells.item(0).innerHTML;
  8.      var Da_ora = oCells.item(1).innerHTML;
  9.      var A_giorno = oCells.item(2).innerHTML;
  10.      var A_ora = oCells.item(3).innerHTML;
  11.      var Da_giorno = oCells.item(4).innerHTML;
  12.      var Tipo_assenza = oCells.item(5).innerHTML;
  13.      var Data_dichiarazione = oCells.item(6).innerHTML;
  14.                
  15.      var myData = {
  16.          "myData": {
  17.          "Nome": Nome,
  18.          "Da_ora": Da_ora,
  19.          "A_giorno": A_giorno,
  20.          "A_ora": A_ora,
  21.          "Da_giorno": Da_giorno,
  22.          "Tipo": Tipo_assenza,
  23.          "Data_dichiarazione": Data_dichiarazione
  24.           }
  25.      };
  26.  
  27.      $.ajax({
  28.           url: "http://localhost:8080/FastNew/ServletDownloadAssenze",
  29.           type: "get",
  30.           data: {
  31.                jsonData: JSON.stringify(myData)
  32.           },
  33.           cache: false,
  34.           dataType: "json"
  35.       });
  36.                
  37.      $("table[id^='table']").DataTable();
  38.      }
  39.  
  40.      $("table[id^='table']").DataTable();



codice della servlet
Codice sorgente - presumibilmente Java

  1. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  2.             throws ServletException, IOException {
  3.         try {
  4.             processRequest(request, response);
  5.         } catch (ClassNotFoundException ex) {
  6.             Logger.getLogger(ServletDownloadAssenze.class.getName()).log(Level.SEVERE, null, ex);
  7.         } catch (SQLException ex) {
  8.             Logger.getLogger(ServletDownloadAssenze.class.getName()).log(Level.SEVERE, null, ex);
  9.         } catch (JSONException ex) {
  10.             Logger.getLogger(ServletDownloadAssenze.class.getName()).log(Level.SEVERE, null, ex);
  11.         }
  12.     }
  13.  
  14. protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ClassNotFoundException, SQLException, JSONException {
  15.         response.setContentType("text/html;charset=UTF-8");
  16.  
  17.         JSONObject newObj = new JSONObject();
  18.         ;
  19.         try {
  20.                 // parsing del Json
  21.          }
  22.             //chiamata al metodo per generazione e download pdf
  23.             service(request, response, values);
  24.            
  25.         } catch (JSONException e) {
  26.             e.printStackTrace();
  27.         }
  28.  
  29.     }
  30.  
  31.     public void service(HttpServletRequest request, HttpServletResponse response, String[] values) throws ServletException, IOException, ClassNotFoundException, SQLException {
  32.         try {
  33.  
  34.             Document document = new Document();
  35.             ByteArrayOutputStream baos = new ByteArrayOutputStream();
  36.             PdfWriter.getInstance(document, baos);
  37.    
  38.             //generazione del document    
  39.  
  40.             document.close();
  41.  
  42.             response.setHeader("Expires", "0");
  43.  
  44.             String fileName = beanAutista.getNome_Completo() + " " + values[5] + " " + values[2] + ".pdf";
  45.             response.setHeader("Content-disposition", "attachment;filename=" + fileName);
  46.            
  47.             response.setContentType("application/pdf");
  48.  
  49.             response.setContentLength(baos.size());
  50.  
  51.             OutputStream os = response.getOutputStream();
  52.             baos.writeTo(os);
  53.             os.flush();
  54.             os.close();
  55.            
  56.            
  57.         } catch (DocumentException e) {
  58.             throw new IOException(e.getMessage());
  59.         }




PM Quote
Avatar
pierotofy (Admin)
Guru^2


Messaggi: 6230
Iscritto: 04/12/2003

Segnala al moderatore
Postato alle 18:14
Lunedì, 22/08/2016
Non puoi scaricare files via Ajax.

Codice sorgente - presumibilmente Plain Text

  1. location.href = "http://localhost:8080/FastNew/ServletDownloadAssenze?" + $.param(myData)



Il mio blog: https://piero.dev
PM Quote
Avatar
TheDarkJuster (Member)
Guru^2


Messaggi: 1620
Iscritto: 27/09/2013

Segnala al moderatore
Postato alle 18:58
Lunedì, 22/08/2016
Quello che dice piero non è del tutto corretto: nei più moderni browsers è possibile adottare soluzioni in stile mega.co scaricando il file in un buffer e usando estensioni js native del browser per salvarlo: http://stackoverflow.com/questions/15994554/download-files ...

ma sicuramente la soluzione di piero è la migliore dal punto di vista facilità implementativa e compatibilità!

Ultima modifica effettuata da TheDarkJuster il 22/08/2016 alle 19:00
PM Quote
Avatar
pierotofy (Admin)
Guru^2


Messaggi: 6230
Iscritto: 04/12/2003

Segnala al moderatore
Postato alle 20:27
Lunedì, 22/08/2016
Si, hai ragione.


Il mio blog: https://piero.dev
PM Quote