2015-08-11 3 views
0

Я использую сервлет для загрузки PDF-файла из своей БД и распечатываю его на HTML <object> на странице.
На моей странице есть кнопка загрузки, передающая параметр сервлету и загрузка другого файла из моей БД. Мой PDF-сервлет отлично работает, но не получает параметр со страницы JSP, чтобы загрузить файл на странице.
Пример: У меня есть запрос SELECT на моем PDF-сервлете, чтобы получить правильный файл PDF: select pdf from pdf where id = ?, проблема в том, что сервлет не может получить параметр со страницы и поместить его в мой запрос ?. Но если я делаю это вручную, как select pdf from pdf where id = 1, то моя страница загружает PDF-файл.
Это мой index.jsp:Пропустить параметр для сервлета при загрузке страницы

<%-- 
    Document : index 
    Created on : 06/08/2015, 16:14:51 
    Author  : Henrique 
--%> 

<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<!DOCTYPE html> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <title>JSP Page</title> 
    </head> 
    <body>   
     <h1>Teste Download XML</h1> 
     <form action="${pageContext.request.contextPath}/downloadDB"> 
      <input type="hidden" name="id" value="<%=request.getParameter("id")%>" /> 
      <button type="submit">Download</button> 
     </form> 

     <object data="pdf" type="application/pdf" width="1000" height="1000"/> 
    </body> 
</html> 

Это мой DisplayPDF Servlet doGet метод:

@Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
     int uploadId = Integer.parseInt(request.getParameter("id")); 

     Connection conn = null; // connection to the database 

     try { 
      // connects to the database 
      DriverManager.registerDriver(new com.mysql.jdbc.Driver()); 
      conn = DriverManager.getConnection(dbURL, dbUser, dbPass); 

      // queries the database 
      String sql = "SELECT * FROM xmlNFe WHERE xml_id = ?"; 
      PreparedStatement statement = conn.prepareStatement(sql); 
      statement.setInt(1, uploadId); 
      ResultSet result = statement.executeQuery(); 

      if (result.next()) { 
       Blob blob = result.getBlob("xml_pdf"); 
       InputStream inputStream = blob.getBinaryStream(); 
       String fileName = result.getString("xml_chnfe"); 
       int fileLength = inputStream.available(); 

       System.out.println("fileLength = " + fileLength); 

       ServletContext context = getServletContext(); 

       // sets MIME type for the file download 
       String mimeType = context.getMimeType(fileName); 
       if (mimeType == null) { 
        mimeType = "application/pdf"; 
       } 

       response.setContentType(mimeType); 
       response.setContentLength(fileLength); 
       String headerKey = "Content-Disposition"; 
       String headerValue = String.format("Content-Disposition", "inline; filename=\"" + fileName + "\""); 
       response.setHeader(headerKey, headerValue); 
       OutputStream outputStream = response.getOutputStream(); 

       byte[] buffer = new byte[BUFFER_SIZE]; 
       int bytesRead = -1; 

       while ((bytesRead = inputStream.read(buffer)) != -1) { 
        outputStream.write(buffer, 0, bytesRead); 
       } 

       inputStream.close(); 
       outputStream.close(); 
      } 
     } catch (SQLException ex) { 
      Logger.getLogger(DisplayPDF.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 

И это мой другой сервлет, который вызывается, когда пользователь нажимает на кнопку Загрузить:

@Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
     // get upload id from URL's parameters 
     int uploadId = Integer.parseInt(request.getParameter("id")); 
     Connection conn = null; // connection to the database 

     try { 
      // connects to the database 
      DriverManager.registerDriver(new com.mysql.jdbc.Driver()); 
      conn = DriverManager.getConnection(dbURL, dbUser, dbPass); 

      // queries the database 
      String sql = "SELECT * FROM xmlNFe WHERE xml_id = ?"; 
      PreparedStatement statement = conn.prepareStatement(sql); 
      statement.setInt(1, uploadId); 

      ResultSet result = statement.executeQuery(); 
      if (result.next()) { 
       // gets file name and file blob data 
       String fileName = result.getString("xml_chnfe"); 
       Blob blob = result.getBlob("xml_xml"); 
       InputStream inputStream = blob.getBinaryStream(); 
       int fileLength = inputStream.available(); 

       System.out.println("fileLength = " + fileLength); 

       ServletContext context = getServletContext(); 

       // sets MIME type for the file download 
       String mimeType = context.getMimeType(fileName); 
       if (mimeType == null) { 
        mimeType = "application/octet-stream"; 
       } 

       // set content properties and header attributes for the response 
       response.setContentType(mimeType); 
       response.setContentLength(fileLength); 
       String headerKey = "Content-Disposition"; 
       String headerValue = String.format("attachment; filename=\"%s\"", fileName + ".xml"); 
       response.setHeader(headerKey, headerValue); 

       // writes the file to the client 
       OutputStream outStream = response.getOutputStream(); 

       byte[] buffer = new byte[BUFFER_SIZE]; 
       int bytesRead = -1; 

       while ((bytesRead = inputStream.read(buffer)) != -1) { 
        outStream.write(buffer, 0, bytesRead); 
       } 

       inputStream.close(); 
       outStream.close(); 
      } else { 
       // no file found 
       // response.getWriter().print("File not found for the id: " + uploadId); 
      } 
     } catch (SQLException ex) { 
      ex.printStackTrace(); 
      response.getWriter().print("SQL Error: " + ex.getMessage()); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
      response.getWriter().print("IO Error: " + ex.getMessage()); 
     } finally { 
      if (conn != null) { 
       try { 
        conn.close(); 
       } catch (SQLException ex) { 
        Logger.getLogger(BDFileDownloadServlet.class.getName()).log(Level.SEVERE, null, ex); 
       } 
      } 
     } 
    } 

Если вам нужна дополнительная информация, просто спросите.

ответ

0

Получил решение!
Дело в том, что отсутствовал параметр в вызове сервлетов PDF. Раствор меняется

<object data="pdf" type="application/pdf" width="1000" height="1000"/>

К

<object data="pdf?id=<=%request.getParameter("id")%>" type="application/pdf" width="1000" height="1000"/>

Смежные вопросы