2012-06-15 43 views
0

我是jsp新手,剛剛構建了我的第一個應用程序。我正在閱讀一本書。書中使用的代碼jsp如何向servlet發送請求參數

<form name="addForm" action="ShoppingServlet" method="post"> 
    <input type="hidden" name="do_this" value="add"> 

    Book: 
    <select name="book">     

    <% 
     //Scriplet2: copy the booklist to the selection control 
     for (int i=0; i<bookList.size(); i++) { 

      out.println("<option>" + bookList.get(i) + "</option>"); 

     } //end of for 
    %>     
    </select> 

    Quantity:<input type="text" name="qty" size="3" value="1">    
    <input type="submit" value="Add to Cart"> 

</form> 

,並在servlet代碼

else if(do_This.equals("add")) { 

    boolean found = false; 
    Book aBook = getBook(request); 
    if (shopList == null) { // the shopping cart is empty 

     shopList = new ArrayList<Book>(); 
     shopList.add(aBook); 

    } else {... }// update the #copies if the book is already there 

private Book getBook(HttpServletRequest request) { 

    String myBook = request.getParameter("book"); //confusion 
    int n = myBook.indexOf('$'); 
    String title = myBook.substring(0, n); 
    String price = myBook.substring(n + 1); 
    String quantity = request.getParameter("qty"); //confusion 
    return new Book(title, Float.parseFloat(price), Integer.parseInt(quantity)); 

} //end of getBook() 

我的問題是,當我上添加單擊添加到購物車按鈕,然後在行String myBook = request.getParameter("book");中的servelt我拿到書爲參數,但在我的JSP我沒有說request.setAttribute("book", "book")request.getParameter("qty");相同。我的servlet如何在不將它設置爲jsp代碼的情況下接收這些請求參數? 感謝

回答

2

你得到的參數,因爲在你的表格你有這樣的:

<select name="book"> 

從來沒有一個request.setParameter(這種方法甚至沒有定義)的用戶

您還可以設置一個參數通過用查詢字符串調用該servlet。喜歡的東西:

http://localhost:8080/ShoppingServlet?name=abcd&age=20 

以上將創建一個名爲abcage 2個請求參數,您可以訪問使用request.getParameter

+0

HHMM你的意思是,如果在我的形式我用name屬性的HTML元素(NAME =「XXX」 ),那麼所有的名稱屬性值都會自動添加到httpServletRequest中。是嗎? – Basit

+0

這是正確的。 – adarshr

+0

但是你必須理解'request parameters'和'request attributes'之間的區別。 – adarshr

相關問題