i am new to jsp and just built my first application. I am following a book. The book used a code
<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>
and in the servlet the code is
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()
My question is when i click on add Add to Cart button then in the servelt at line String myBook = request.getParameter("book"); i get book as a parameter but in my jsp i didn’t say that request.setAttribute("book", "book"), same for request.getParameter("qty");. How my servlet is receiving these request parameters without setting it in jsp code?
Thanks
You get that parameter because in your form you have this:
The user never does a
request.setParameter(such a method is not even defined)You can also set a parameter by invoking the servlet with a query string. Something like:
The above will create two request parameters named
abcandagewhich you can access usingrequest.getParameter