【问题标题】:Pass data to servlet将数据传递给 servlet
【发布时间】:2014-01-11 22:23:02
【问题描述】:

我有一个包含几个字段的 jsp 页面。我需要在 servlet 中使用其中一些字段来获取 Car 的详细信息。这是jsp页面中的表格:

<form method="post" action="Update">  
                <table id="centerTable" width="600">
                   <tr>                              
                       <th><h5>Car ID</h5></th>
                       <th><h5>Car Brand</h5></th>
                    </tr>                           
                    <tr>
                        <td>${bookedCar.id}</td>
                        <td>${bookedCar.carbrand}</td>
                    </tr>                 
                </table>

                </br></br>                                    
                <p class="submit"><input type="submit" value="Cancel Booking"></p>

 </form>

在 servlet Update.java 中,我在 doPost 中有以下内容。我需要在更新 servlet 中使用汽车 ID,但我一直将值设为 null。我是否错误地调用了该属性?

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {


    Cars myCar = (Cars)request.getAttribute("bookedCar");
    String carID = (String)request.getAttribute("bookedCar.id");

【问题讨论】:

    标签: jsp servlets attributes


    【解决方案1】:

    您首先需要在表单提交中发送信息,因此您需要使用输入标签发送此信息所以这样更改表格:

    <form method="post" action="Update">  
        <table id="centerTable" width="600">
            <tr>                              
                <th><h5>Car ID</h5></th>
                <th><h5>Car Brand</h5></th>
            </tr>                           
            <tr>
                <td><input type="text" name="bookedCarId" value="${bookedCar.id}" readonly/></td>
                <td><input type="text" name="bookedCar" value="${bookedCar.carbrand}"  readonly/></td>
           </tr>                 
         </table>
         </br></br>                                    
         <p class="submit"><input type="submit" value="Cancel Booking"></p>
    </form>
    

    要获取表单提交中发送的值,您需要使用输入标签的 name 属性,但使用 HttpServletRequest 对象中的 getParameter 函数,因此:

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    
    
        String myCar = request.getParameter("bookedCar");
        String carID = request.getParameter("bookedCarId");
    }
    

    如您所见,此方法获取请求中发送的字符串参数,使用此信息您可以获取汽车对象,或者您可以将此对象存储为会话对象的属性,以便在下一个请求中获取此对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-06
      • 2012-12-15
      • 2014-05-02
      • 1970-01-01
      • 2012-09-24
      • 2010-09-19
      • 1970-01-01
      相关资源
      最近更新 更多