【问题标题】:Pass parameter to Servlet on page load在页面加载时将参数传递给 Servlet
【发布时间】:2015-08-11 14:31:13
【问题描述】:

我正在使用 Servlet 从我的数据库中加载 PDF 文件并将其显示在页面上的 HTML <object> 上。
我的页面包含一个下载按钮,该按钮将参数传递给 servlet 并从我的数据库下载另一个文件。我的 PDF Servlet 工作正常,但没有从我的 JSP 页面获取参数以在页面上加载文件。
例如:我的 PDF Servlet 上有一个SELECT 查询以获取正确的 PDF 文件: select pdf from pdf where id = ?,问题是servlet 无法从页面中获取参数并将其放入我的? 查询中。但是,如果我像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);
        }
    }

这是我在用户单击“下载”按钮时调用的另一个 servlet:

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

如果您需要更多详细信息,请询问。

【问题讨论】:

    标签: jsp servlets parameters load parameter-passing


    【解决方案1】:

    找到了解决方案!
    问题是它缺少 PDF servlet 调用中的参数。解决方案正在改变

    &lt;object data="pdf" type="application/pdf" width="1000" height="1000"/&gt;

    By

    &lt;object data="pdf?id=&lt;=%request.getParameter("id")%&gt;" type="application/pdf" width="1000" height="1000"/&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-06
      • 1970-01-01
      相关资源
      最近更新 更多