【问题标题】:Handling multiple submit buttons with JSP and Servlets使用 JSP 和 Servlet 处理多个提交按钮
【发布时间】:2015-09-29 14:36:48
【问题描述】:

我有一个从数据库生成的表。该表将附在表格中。以下是浏览器上的结果:

http://i.imgur.com/NLZzgwP.png(低代表问题)

以下是 JSP/JSTL 代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Issues</title>
<style type="text/css">
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
td {
padding: 10px;
}
</style>
</head>
<body>
<sql:setDataSource
var="myDS"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/pdfdb"
user="user" password="*******"
/>
<sql:query var="listIssues" dataSource="${myDS}">
 SELECT BookId from Book;
</sql:query>

    <form method="get" action="fileDownload">
        <div align="center">
            <table>
                <caption>List of Issues</caption>
                    <tr>
                        <th>Magazine Issue #</th>
                        <th>Download</th>
                    </tr>
                    <c:forEach var="issue" items="${listIssues.rows}">
                    <tr>
                        <td><c:out value="${issue.BookId}" /></td>
                        <td><input name='<c:out value="${issue.BookId}" />' type="submit" value="Download"></td>        
                    </tr>
                    </c:forEach>
            </table>
        </div>
    </form>
</body>
</html>

现在,我想要的是让下载按钮与 id/Issue 编号相关联,该编号与按钮位于同一行,这样,当用户单击下载按钮时,它会传递 id/杂志期号到 url,告诉浏览器用户想要下载该按钮点击的相应杂志期号。下面是我用来实现这个的 servlet:

package com.mypackage.fileDownload;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



/**
* Servlet implementation class FileDownloadServlet
 */
@WebServlet("/fileDownload")
public class FileDownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

//size of byte buffer to send file
private static final int BUFFER_SIZE = 4096;

//database connection settings
private String dbUrl = "jdbc:mysql://localhost:3306/pdfdb";
private String dbUser = "user";
private String dbPass = "******";

/**
 * @see HttpServlet#doGet(HttpServletRequesrequest,HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //get upload id from URL's parameters
    String uploadId = request.getParameter("name");

    Connection con = null; //connects to the database

    try {
        //connects to the database
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection(dbUrl, dbUser, dbPass);

        //queries the database
        String sql = "SELECT * FROM Book WHERE BookId = ?";
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setString(1, uploadId);

        ResultSet result = pstmt.executeQuery();
        if(result.next()) {
            //gets file name and file blob data
            String fileId = result.getString("BookId");
            Blob blob = result.getBlob("BookContent");
            InputStream inputStream = blob.getBinaryStream();
            int fileLength = inputStream.available();

            System.out.println("File length = " + fileLength);
            ServletContext context = getServletContext();

            //Sets MIME type for the file download
            String mimeType = context.getMimeType(fileId);
            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\"", fileId);

            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());
    } catch(ClassNotFoundException ex) {
        ex.printStackTrace();
        response.getWriter().print("Class Missing Error: " + ex.getMessage());
    }
        finally {
        if(con != null) {
            //closes the database connection 
            try {
                con.close();
            } catch(SQLException ex) {
                ex.printStackTrace();
               }
            }
        }
    }

}

嗯,从我这样做的方式来看,它并没有按照我想要的方式工作。例如,如果您在服务器上运行此代码并单击任何下载按钮,则 url 将类似于

issue.jsp?1=下载

这很奇怪。它也会显示在浏览器上

找不到该 id 的文件:null

我期待类似(在网址上)

issue.jsp?Download=1

其中 1 是正在下载的问题。我的数据库有两列:IssueId 和 fileContent(存储在 BLOB 中的文件内容)。

我想我已经解释得够多了,概念也很清楚。任何帮助将不胜感激,这是我的代码和研究所能做到的。谢谢!

【问题讨论】:

  • 如果您希望按钮提交不同的数据,请使用单独的表单。
  • 如果您希望他们做不同的事情但发送相同的数据,请确保为按钮提供name 属性并使用request.getParameter("name") 获取value(即显示在按钮)并对该值执行 switch case 或 if 语句。
  • 您没有想到您只是混淆了namevalue 属性吗?
  • @developerwjk 我们正在讨论未知数量的按钮,这些按钮会随着时间的推移而不断增加,甚至可能达到 100 个。我认为为每个按钮创建一个表单是不正确的。关于您的第二个答案,这是我做的第一件事,但它不起作用。所有按钮的 value 属性的值为“Download”。
  • @developerwjk 同样,所有的按钮都会发送不同的数据。

标签: sql jsp servlets jstl


【解决方案1】:

最简单的方法就是把表格移到表格里面,做多个表格:

    <div align="center">
        <table>
            <caption>List of Issues</caption>
                <tr>
                    <th>Magazine Issue #</th>
                    <th>Download</th>
                </tr>
                <c:forEach var="issue" items="${listIssues.rows}">
                <tr>
                    <td><c:out value="${issue.BookId}" /></td>
                    <td>
                        <form method="get" action="fileDownload">
                           <input type='hidden' name='bookid' value='<c:out value="${issue.BookId}" />' />
                           <input type="submit" value="Download">
                        </form>
                   </td>        
                </tr>
                </c:forEach>
        </table>
    </div>

您还需要将值从按钮的name 属性中移出,并移到隐藏输入的value 属性中。隐藏的输入需要一个 name,您将使用它来获取 servlet 中的值:request.getParameter("bookid");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多