【问题标题】:Passed data from JSP to Servlet returning null in Servlet将数据从 JSP 传递到 Servlet 在 Servlet 中返回 null
【发布时间】:2014-10-01 21:06:11
【问题描述】:
<table border="1" cellpadding="5" id="newtable">
                <!-- <caption id="tablehead">Rooms are available!</caption> -->

              <!--       <tr class="hover"> -->
                    <tr>
                        <th>Room No</th>
                        <th>AC</th>
                        <th>Deluxe</th>
                        <th>Tariff</th>
                    </tr>
                    <c:forEach var="room" items="${myrooms}">
                        <tr bgcolor="#4B476F" onMouseOver="this.bgColor='gold';" onMouseOut="this.bgColor='#4B476F';">

                            <td class="nr">1</td>
                            <td name="ac"><c:out value="${room.ac}" /></td>
                            <td name="deluxe"><c:out value="${room.deluxe}" /></td>
                            <td>&#8377;<c:out value="${room.price}" /></td>
                            <td><button type="button" class="mybutton" onclick="location.href='passtopayment'">Pay</button> </td>
                        </tr>
                    </c:forEach>
                </table> 

我想在点击相应行时获取 AC 和 Deluxe 列的 td 值。但是,当执行我得到的以下 servlet 代码时,会打印 null null 。请帮忙!

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String ac = request.getParameter("ac");
    String deluxe = request.getParameter("deluxe");

    out.println(ac);
    out.println(deluxe);
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}

【问题讨论】:

  • form 标签在哪里提交到服务器端?
  • 您是如何将请求参数提交给 Servlet 的?
  • 我不确定您的逻辑(td 的名称)将如何工作。你也在迭代列表myrooms。所以可能有 n 行。因此,您无法使用 request.getParameter 接收这些值并将其放入 String 数据类型中。

标签: java html jsp servlets jstl


【解决方案1】:

您正在使用location.href='passtopayment',这不是提交表单的正确方式。

这就像一个对 Servlet 的单独请求,不会向 Servlet 发送任何内容。

您应该使用form 并将请求提交给Servlet。

<form action="passtopayment" method="post">
       <!-- HTML controls -->
       <input type="submit" value="Submit"/>
</form>

这里有详细的Example

【讨论】:

  • 另外,doPostdoGet 不应该有相同的行为。