将数据传递给servlet

时间:2014-01-11 22:23:02

标签: jsp servlets attributes

我有一个包含几个字段的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中使用car 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");

1 个答案:

答案 0 :(得分:0)

首先需要在表单提交中发送信息,因此您需要使用输入标记来发送此信息,因此请以这种方式更改表格:

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

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

相关问题